1
votes

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?

2
If you have any contorl over the xml, I would seriously suggest refactoring it to something more maintainable, eg. <item><a>first</a><b>1st</b></item>. If you can do that, your code becomes cleaner, and less likely to break in the event of needing to add a <c> element later.ZombieSheep

2 Answers

1
votes

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>
0
votes

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"))
    });