c# - XPATH没有返回结果

标签 c# .net xml xpath

我在XMLDocument对象中加载了一些XML。我正在通过使用

For Each node As XmlNode In doc.GetElementsByTagName("Item", [NAMESPACE])
   'Do Stuff
Next


我想在此循环中使用xpath拔出所有名称为“ MyNode”的节点
我以为我只需要做一下node.SelectNodes(“ MyNode”),但这将返回零列表。

<Root>
<Item>
<MyNode></MyNode>
<MyNode></MyNode>
<MyNode></MyNode>
<RandomOtherNode></RandomOtherNode>
<RandomOtherNode></RandomOtherNode>
</Item>
<MyNode></MyNode>
<MyNode></MyNode>
<MyNode></MyNode>
<RandomOtherNode></RandomOtherNode>
<RandomOtherNode></RandomOtherNode>
<Item>
</Item>
<Item>
<MyNode></MyNode>
<MyNode></MyNode>
<MyNode></MyNode>
<RandomOtherNode></RandomOtherNode>
<RandomOtherNode></RandomOtherNode>

</Item>
</Root>


我需要做些额外的事情吗?

最佳答案

XPATH的“ MyNode”应该可以工作,我想您的[NAMESPACE]错误。尝试在不使用NAMESPACE的情况下调用GetElementsByTagName()。要么查看循环中的代码,然后确保您没有格式错误的WriteLine()或其他内容。

请原谅以下C#示例,因为我很少使用VB。它表明您的XPATH是正确的...

string xml = @"
<Root> 
    <Item> 
        <MyNode></MyNode> 
        <MyNode></MyNode> 
        <MyNode></MyNode> 
        <RandomOtherNode></RandomOtherNode> 
        <RandomOtherNode></RandomOtherNode> 
    </Item> 
    <MyNode></MyNode> 
    <MyNode></MyNode> 
    <MyNode></MyNode> 
    <RandomOtherNode></RandomOtherNode> 
    <RandomOtherNode></RandomOtherNode> 
    <Item> 
    </Item> 
    <Item> 
        <MyNode></MyNode> 
        <MyNode></MyNode> 
        <MyNode></MyNode> 
        <RandomOtherNode></RandomOtherNode> 
        <RandomOtherNode></RandomOtherNode> 

    </Item> 
</Root> 
";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        foreach (XmlNode node in doc.GetElementsByTagName("Item"))
        {
            foreach (XmlNode n2 in node.SelectNodes("MyNode"))
                Console.WriteLine("{0}:{1}", node.Name, n2.Name);
        }

关于c# - XPATH没有返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3948448/

相关文章:

c# - 如果文件夹包含空格,如何处理文件路径中的空格?

xml - 澄清我在 web.xml 中的 servlet 映射错误

xml - 在 Windows Phone 中使用 HttpWebRequest 获取 xml

c# - 封装一个任务来记录异步函数的持续时间

c# - 如何从不同的输入插入

c# - 何时在 C# 单元测试中使用模拟与伪造?

.net - 删除 Azure 上的特定 Application Insights 事件

c# - 将 >48k 发送到 WCF 数据服务 (OData) 413 错误

c# - NHibernate 3、动态组件、字典和 LINQ 查询

xml - 如何在 Word 中使用 XSL 设计导入的 XML?