简体   繁体   English

如何使用命名空间获取xml元素

[英]how to get the xml element with namespaces

I recently started learning xml, xpath, xmldocuemtn in c#. 我最近开始在C#中学习xml,xpath,xmldocuemtn。

I have an xml as shown bellow..namespaces is confusing me a lot 我有一个XML,如下所示。.namespaces让我很困惑

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:x="urn:schemas-microsoft-com:office:excel"
   xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
   xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="Pricing">
</Worksheet>
<Worksheet ss:Name="Order">
</Worksheet>
</Workbook>

Here is my c# code.. 这是我的C#代码。

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

Can you tell me how i can get Worksheet elemet with ss:Name attribute='Pricing' 您能告诉我如何使用ss:Name attribute ='Pricing'获取工作表要素吗?

You have to use XmlNamespaceManager to provide namespaces: 您必须使用XmlNamespaceManager提供名称空间:

var namespaceMgr = new XmlNamespaceManager(doc.NameTable);
namespaceMgr.AddNamespace("x", "urn:schemas-microsoft-com:office:spreadsheet");
namespaceMgr.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");
var node = doc.SelectSingleNode("//x:Worksheet[@ss:Name='Pricing']", namespaceMgr);

Note that prefixes for namespaces not must match those from XML - the value of namespace counts. 请注意,名称空间的前缀必须与XML中的前缀不匹配-名称空间计数的值。 So, for example, I've defined ss as in XML, but default (root) namespace I've named x - it does not matter as long as its value is the same. 因此,例如,我已经在XML中定义了ss ,但是默认的(根)命名空间中我已将其命名为x -没关系,只要其值相同即可。

To be more strict, you can change XPath to /x:Workbook/x:Worksheet[@ss:Name='Pricing'] of course. 更严格地说,您当然可以将XPath更改为/x:Workbook/x:Worksheet[@ss:Name='Pricing']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM