0

I have 4 similar nodes with 4 different values. For example, I have the below values.

<sample>
        <a>123</a>
        <a>45</a>
        <a>67</a>
        <a>890</a>
</sample>

I need to check the length of each node and if its less than 3, then leading zeroes should be appended like below.

<sample>
        <a>123</a>
        <a>045</a>
        <a>067</a>
        <a>890</a>
</sample>

After appending leading zeroes, I need to concatenate all the values together and pass it as a single string.

<a>123045067890</a>

Please provide an optimum solution.

Black Pearl
  • 79
  • 1
  • 2
  • 9

3 Answers3

1

here's one approach using XPath:

string xml = @"
    <sample>
        <a>123</a>
        <a>45</a>
        <a>67</a>
        <a>890</a>
    </sample>
";

//load xml
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(xml);

//get all <a> nodes and cast them to List<XmlNode>
var nodes = xdoc.SelectNodes("sample/a")
    .Cast<XmlNode>().ToList();

//iterate through each node and append leading zeroes until length is 3 chars
nodes.ForEach(n => n.InnerText = n.InnerText.PadLeft(3, '0'));
//join all values and add tags to beginning and the end
string concatenatedValues = "<a>" + string.Join("", nodes.Select(x => x.InnerText).ToArray()) + "</a>";
Nino
  • 6,931
  • 2
  • 27
  • 42
1

The following stylesheet:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="sample">
    <a>
        <xsl:for-each select="a">
            <xsl:value-of select="format-number(., '000')" />
        </xsl:for-each>
    </a>
</xsl:template>

</xsl:stylesheet>

applied to your example input, returns:

<?xml version="1.0" encoding="UTF-8"?>
<a>123045067890</a>
michael.hor257k
  • 113,275
  • 6
  • 33
  • 51
0

You can try this:

string xml = @"<sample>
                        <a>123</a>
                        <a>45</a>
                        <a>67</a>
                        <a>890</a>
                    </sample>";

XDocument xmlDoc = XDocument.Parse(xml);
int value = 0;
StringBuilder errorsSb = new StringBuilder();
List<string> a_Nodes = new List<string>();

xmlDoc.Descendants("a").Select(x => x.Value).ToList().ForEach(x =>
{
     if (int.TryParse(x, out value))
          a_Nodes.Add(value.ToString("D3"));
     else
          errorsSb.AppendLine($"Value {value} is not a number");
     });

     string res = String.Join(string.Empty, a_Nodes);
     if (!string.IsNullOrWhiteSpace(errorsSb.ToString()))
     {
          // handle errors
     }
}
daniell89
  • 1,832
  • 16
  • 28