我有一个对象' xmlResponse'包含以下XML数据的XDocument类型:
<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>
但是在尝试提取值并将它们附加到文本框时,我发现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");
}
关于我在网上看过的例子,所以我不确定我做错了什么,或者foreach中的代码是否能正常工作。我想做的只是将文字附加到&#39; resultTextBox&#39;像这样:
1 Paul Deitel
2 Harvey Deitel
3 Abbey Deitel
非常感谢任何帮助,非常感谢您。
答案 0 :(得分:2)
您错过了使用AuthorEntry
的默认命名空间前缀:
XNamespace xmlNamespace = "http://schemas.datacontract.org/2004/07/BooksService";
.....
foreach (XElement elem in xmlResponse.Descendants(xmlNamespace + "AuthorEntry"))