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

3

本文介绍了如何选择使用默认命名空间的节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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.

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

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14