1

I need to convert a specific part of an XML file to string, with the data in it varying. eg.

I have an xml file with this portion in it: -<root>-<Data><1>data</1>

and I want to only convert that line to a string, not the entire file. This, I know how to do. My issue is that the data in "1" will change depending on the circumstances, and I still want to be able to use the same program to convert it regardless of what the data in "1" reads.

to read the "1" line without verying data I know I can use:

 var xml = "<root><Data><1>data</1></Data></root>";   
var xmlString = XElement.Parse(xml).Descendants("1").FirstOrDefault().Value;

but I don't know how to do it with the contents of "1" changing.

4
  • Is the <1> element always a singular leaf? In other words, does it have any siblings or is it the only child element of <Data>? Commented May 21, 2012 at 2:36
  • One thing to note is that FirstOrDefault could return null, making the .Value call an exception. I'd just use .First, so the exception makes more sense. Commented May 21, 2012 at 2:45
  • Thanks, I will take note of that @YuriyFaktorovich Commented May 21, 2012 at 2:53
  • It is the only child of data @casperOne but data is not the only child of root Commented May 21, 2012 at 2:54

1 Answer 1

1
var xml = "<root><Data><One>data</One></Data></root>";

var xmlString = (from data in XElement.Parse(xml).Descendants("Data")
                 where data.Descendants().Any()
                 select data.Descendants().First().Value).FirstOrDefault();

Side note: having an XML element whose name begins with a number is considered invalid XML, and as such, XElement will fail to parse it.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, and thank you for pointing out that I couldn't use "1"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.