Breaking up XML string in C#
Question
I have got an XML node called 'structNumber' which has data similar to '4.2'
I select the node using:
XmlNode xnChapNr = xDoc.SelectSingleNode("//./structNumber");
And at present I am displaying it by:
string chapNr = (xnChapNr == null) ? "X" : xnChapNr.InnerText
This then displays the entire string '4.2'.
What I need however, is a way to only select the '4' for this string and the '2' for another.
Is there an extension for InnerText? I have read through the documentation but nothing appears to work as I wish it to.
If it is helpful to know; what this code does in its entirety is produce a tree structure of an XML document. I.e: Chapter 4, Section 4.1, Sub section 4.1.1, Section 4.2, ect...
Any and all help will be much appreciated.
Solution
string chapNr = (xnChapNr == null) ? "X" : xnChapNr.InnerText.ToString().Split(new char[]{'.'})[0]
will return you 4 and
string chapNr = (xnChapNr == null) ? "X" : xnChapNr.InnerText.ToString().Split(new char[]{'.'})[1]
will return you 2
OTHER TIPS
What you are looking for is not related to XML but to String operation. What you are looking for is the Split function http://msdn.microsoft.com/en-us/library/b873y76a.aspx