[英]C# can't query XML but can traverse the nodes?
與我的其他問題有關。
我正在嘗試從 XML 文件中讀取一個節點,如下所示:
<?xml version="1.0" encoding="UTF-8" ?>
<AuthorIT>
<Objects>
<Media>don't care</Media>
<Style>don't care</Style>
<Book>don't care</Book>
<Topic>don't care</Topic>
<Topic>
<Object>
<Description>Performance Evidence</Description>
</Object>
<Text>This is what I want to select</Text>
</Topic>
</Objects>
</AuthorIT>
但我無法查詢。 我試過 XmlDocument、XPath 和 Linq 到 XML。
我已經在http://XPather.com上驗證了我的 XPath 是正確的。
/* this doesn't work but the XPath has been verified */
XPathNavigator nav;
XPathDocument docNav;
string xPath;
docNav = new XPathDocument(localFile);
nav = docNav.CreateNavigator();
xPath = "//Topic[Object/Description = 'Performance Evidence']/Text";
string value = nav.SelectSingleNode(xPath).Value;
我可以使用 XmlDocument 遍歷 XML 節點,但我不希望使用一系列嵌套的 foreach 循環來代替單個查詢。
XmlDocument doc = new XmlDocument();
doc.Load(localFile);
XmlNodeList xmlNodes = doc.SelectNodes("/");
/* direct query doesn't work, but traversing the nodes does? */
foreach (XmlNode node in xmlNodes)
{
if (node.Name == "#document")
{
foreach (XmlNode subNode in node.ChildNodes)
{
if (subNode.Name == "AuthorIT")
{
foreach (XmlNode subSubNode in subNode.ChildNodes)
{
if (subSubNode.Name == "Objects")
{
foreach (XmlNode subSubSubNode in subSubNode.ChildNodes)
{
if (subSubSubNode.Name == "Topic")
{
// I didn't finish writing this, because it's a ridiculous way to do it... but it works
}
}
}
}
}
}
}
}
有什么我做錯了嗎?
XML 文檔的某些屬性會導致這種情況嗎? (如果是這樣,我該如何解決?)
如果您想要的只是存儲在<Text>
屬性中的值,則無需遍歷所有內容,請嘗試以下操作:
var doc = XDocument.Parse(File.ReadAllText(filePath));
var value = doc.XPathSelectElement("/AuthorIT/Objects/Topic/Text").Value;
我在示例 XML 中遺漏的是解決方案的關鍵......命名空間!
我在另一個問題上找到了答案: Using Xpath With Default Namespace in C#
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.