Reputation: 2586
i am trying to read an xml file, the format of the file as follow:
<rootnode>
<a>first<b>1st</b></a>
<a>second<b>2nd</b></a>
</rootnode>
i tried to use XDocument like this:
XDocument loadedData = XDocument.Load("file.xml");
var data = from query in loadedData.Descendants("a")
select new myClass
{
Word = (string)query.Value,
secondWord = (string) query.Element("b")
};
but it didnt work, as the (string)query.Value will bring me the whole line;"first1st"
is there any way to get the text instead of the whole element?
Upvotes: 1
Views: 654
Reputation: 29963
I'm not really in a position to do much exploration of the "correct" way to handle this in the XML, but how about if you did some string manipulation on the result?
var data = from query in loadedData.Descendants("a")
select new myClass
{
Word = (string)query.Value.Substring(0, ((string)query.Value).Length - ((string)query.Element("b").Value).Length),
secondWord = (string)query.Element("b")
};
Ugly, but it works. I'm sure there's a "better" way, but as I say, I don't have enough bandwidth to look into it at the moment.
EDIT
As I mentioned in a comment to the original question, if you are in control of writing the XML in the first place, it would be better to reformat it - possibly like this.
<rootnode>
<item><a>first</a><b>1st</b></item>
<item><a>second</a><b>2nd</b></item>
</rootnode>
Not only does this enable you to tidy up the code to get clean values, but allows flexibility to add more data items inside each element if needs be. e.g.
<rootnode>
<item><a>first</a><b>1st</b><c>primary</c></item>
<item><a>second</a><b>2nd</b><c>secondary</c></item>
</rootnode>
Upvotes: 1
Reputation: 33122
You need to change your Descendants to be from "rootnode" rather than "a". Try this:
XDocument loadedData = XDocument.Load("file.xml");
var data = (from query in loadedData.Descendants("rootnode")
select new myClass
{
Word = (string)query.Element("a"),
secondWord = ((string)query.Element("b"))
});
Upvotes: 0