1

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?

1
  • 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. Commented Jul 12, 2011 at 12:22

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.