如何选择使用默认命名空间的节点?

How do I select nodes that use a default namespace?(如何选择使用默认命名空间的节点?)
本文介绍了如何选择使用默认命名空间的节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XML文件的结构大致如下:

The structure of the XML file is more or less as follows:

<?xml version="1.0" encoding="UTF-8"?>
<a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="url1" xsi:schemaLocation="url2 url3">
   <b>
     <c></c>
     <c></c>
     <c></c>
   </b>
</a>

我的目标是选择所有c"元素,但以下 xpath 表达式不起作用://a/b/c".

My goal is to select all the "c" elements, but the following xpath expression won't work: "//a/b/c".

即:

XmlDocument doc= new XmlDocument();
doc.Load(filepath);
XmlNodeList l = doc.SelectNodes("//a/b/c"); // 0 nodes

我测试过的唯一有效的 xpath 表达式是/*(1 个节点)和//*(所有节点).

The only xpath expressions I tested that worked are /* (1 node) and //* (all nodes).

这个问题与 XML 命名空间有关吗?如果是这样,设置 XMLDocument 对象的正确方法是什么?

Is this problem related to the XML namespace? If so, what's the proper way to set up the XMLDocument object?

        XmlDocument doc= new XmlDocument();
        doc.Load(filepath);
        XmlNamespaceManager m = new XmlNamespaceManager(doc.NameTable);
        m.AddNamespace(/* what goes here? */);
        XmlNodeList l = doc.SelectNodes("//a/b/c", m);

推荐答案

你需要为文档使用的默认命名空间分配一个命名空间前缀,然后在你的 XPath 中使用它:

You need to assign a namespace prefix for the default namespace that the document is using, and then use that in your XPath:

XmlDocument doc= new XmlDocument();
doc.Load(filepath);

XmlNamespaceManager m = new XmlNamespaceManager(doc.NameTable);
m.AddNamespace("myns", "url1");

XmlNodeList l = doc.SelectNodes("/myns:a/myns:b/myns:c", m);

您可以将前缀myns"替换为基本上任何内容(不带空格的字母数字),只要它在第 4 行和 XPath 之间保持一致,并且正确分配给第 4 行中的url1"命名空间.

You can replace the prefix "myns" with essentially anything (alphanumeric without spaces), as long as it's consistent between line 4 and the XPath, and that it's correctly assigned to the "url1" namespace in line 4.

这篇关于如何选择使用默认命名空间的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)