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.
这篇关于如何选择使用默认命名空间的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何选择使用默认命名空间的节点?
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30