使用命名空间查询 XML 文档 [英] Query XML Document with Namespaces

查看:40
本文介绍了使用命名空间查询 XML 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文件片段,如下所示:

I have a snippet of an XML file that looks like:

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCatalogItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <CatalogItem>
        <ID xmlns="http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices">bbe9b897-5d3b-4340-914b-fce8d6022bd9</ID>
        <Name xmlns="http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices">EmployeeReport</Name>
    </CatalogItem>

现在我正在尝试查询所有 Name 元素的文件.我知道我可以使用 SelectNodes("//Name") 给我我想要的.但是,由于我在 中有命名空间,所以我必须考虑到这一点.所以这是我到目前为止的代码:

Now I'm trying to query the file for all the Name elements. I'm aware that I can use the SelectNodes("//Name") to give me what I want. However, since I have namespaces in the <ArrayOfCatalogItem> I have to account for that. So here's the code I have so far:

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(@"C:\CatalogItems.xml");

// Create an XmlNamespaceManager for resolving namespaces
System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");

System.Xml.XmlNodeList nodeList;
System.Xml.XmlNode root = doc.DocumentElement;

nodeList = root.SelectNodes("//Name", nsmgr);
Console.WriteLine("There are {0} items.", nodeList.Count);
foreach (System.Xml.XmlNode item in nodeList)
{
    Console.WriteLine(item.InnerText);
}

但是,我遇到的问题是 标记中的命名空间定义.考虑到每个 都有一个定义为属性的命名空间,我将如何查询文档的所有 Name 值?

However, the problem I'm having is the namespace definitions in the <Name> tag. How would I query the document for all Name values taking into account each <Name> has a namespace defined as an attribute?

推荐答案

您使用了错误的 XML 命名空间 - 您需要使用应用于 标记的命名空间 -不是文档默认命名空间(xsd:xsi: 前缀).

You're using the wrong XML namespace - you need to use the one that is applied to the <Name> tag - not the document default namespaces (xsd: and xsi: prefixes).

试试这个:

using System.Xml;

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\CatalogItems.xml");

// Create an XmlNamespaceManager for resolving namespaces
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("rs", "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices");

XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;

nodeList = root.SelectNodes("//rs:Name", nsmgr);

Console.WriteLine("There are {0} items.", nodeList.Count);

foreach (XmlNode item in nodeList)
{
    Console.WriteLine(item.InnerText);
}

这篇关于使用命名空间查询 XML 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆