简体   繁体   English

如何操作XDocument对象

[英]How to manipulate an XDocument object

I have an object 'xmlResponse' of type XDocument which contains the following XML data: 我有一个XDocument类型的对象'xmlResponse',其中包含以下XML数据:

<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语句中的代码由于某些原因永远不会运行:

            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. 从我在网上看到的示例开始,所以我不确定我在做什么错,或者不确定foreach中的代码是否可以正常工作。 What I'd like to do is simply append the text to 'resultTextBox' like so: 我想做的就是将文本追加到“ resultTextBox”中,如下所示:

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 : 您错过了为AuthorEntry使用默认名称空间前缀的AuthorEntry

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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