C#无法查询XML,但可以遍历节点吗?

问题描述 投票:0回答:1

my other question有关。

我正在尝试从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文档的某些属性会导致这种情况? (如果是这样,我该如何解决?)

c# xml xpath linq-to-xml xmldocument
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.