简体   繁体   中英

How to manipulate an XDocument object

I have an object 'xmlResponse' of type XDocument which contains the following XML data:

<ArrayOfAuthorEntry xmlns="http://schemas.datacontract.org/2004/07/BooksService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <AuthorEntry>
    <AuthorID>1</AuthorID>
    <FirstName>Paul</FirstName>
    <LastName>Deitel</LastName>
  </AuthorEntry>
  <AuthorEntry>
    <AuthorID>2</AuthorID>
    <FirstName>Harvey</FirstName>
    <LastName>Deitel</LastName>
  </AuthorEntry>
  <AuthorEntry>
    <AuthorID>3</AuthorID>
    <FirstName>Abbey</FirstName>
    <LastName>Deitel</LastName>
  </AuthorEntry>
</ArrayOfAuthorEntry>

But in trying to extract values and appending them to a text box, I find the code inside the foreach statement never runs for some reason:

            foreach (XElement elem in xmlResponse.Descendants("AuthorEntry"))
            {
                // this line never runs confirming code inside foreach never even reached
                resultTextBox.AppendText("Test");

                // can't even confirm if following lines will work correctly as a result
                resultTextBox.AppendText(elem.Element(xmlNamespace + "AuthorID").Value + " ");
                resultTextBox.AppendText(elem.Element(xmlNamespace + "FirstName").Value + " ");
                resultTextBox.AppendText(elem.Element(xmlNamespace + "LastName").Value + "\n");
            }

Going off of examples I've seen online so I'm not sure what I'm doing wrong or if the code inside the foreach will even work. What I'd like to do is simply append the text to 'resultTextBox' like so:

1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel

Any help is appreciated and thank you very much in advance.

You missed to use the default namespace prefix for AuthorEntry :

XNamespace xmlNamespace = "http://schemas.datacontract.org/2004/07/BooksService";
.....
foreach (XElement elem in xmlResponse.Descendants(xmlNamespace + "AuthorEntry"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM