本文介绍了如何使用NamspaceManager解析在C#中的XML,XML具有被命名空间的元素级别定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望来解析下面的XML

i wish to parse following XML

<?xml version="1.0" encoding="UTF-8"?>
<product xmlns="http://products.org"> 
    <make xmlns="http://camera.org">
 <model>Camry</model> 
</make>
 <make xmlns="http://tv.org">
   <model>Sony</model>
</make>
</product>

code写入解析

Code written to parse it

这就是我正在写解析code

This is how i m writing Parsing Code

但在过去的我为得到空inxmlNode对象。 u能告诉什么更多的事情要做。

but in last i m getting null inxmlNode object. Can u tell what more to do .

推荐答案

您不能忽略XPath名称空间。*文档中的所有元素都具有非空的命名空间URI的。

You can't ignore namespaces in XPath.* The elements in your document all have non-blank namespace URI's.

您的问题标题表明你是在正确的轨道:您需要明确绑定的URI来使用的XmlNamespaceManager,并利用这些prefixes在你的路径前pressions prefixes

Your question title indicates you're on the right track: you need to explicitly bind the URI's to prefixes using an XmlNamespaceManager, and use those prefixes in your path expressions.

本程序是针对您的输入文档测试

This program is tested against your input document

using System;
using System.Xml;

public class XPathNamespace
{
    public static void Main() {

        XmlDocument doc = new XmlDocument();
        doc.Load("test1.xml");

        XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
        xnm.AddNamespace("p", "http://products.org");
        xnm.AddNamespace("c", "http://camera.org");
        xnm.AddNamespace("t", "http://tv.org");

        ShowNode(doc.SelectSingleNode("/p:product", xnm));
        ShowNode(doc.SelectSingleNode("/p:product/c:make", xnm));
        ShowNode(doc.SelectSingleNode("/p:product/t:make", xnm));
    }

    private static void ShowNode(XmlNode node) {
        Console.WriteLine("<{0}> {1}",
                          node.LocalName, 
                          node.NamespaceURI);
    }
}

和它产生以下输出

<product> http://products.org
<make> http://camera.org
<make> http://tv.org

希望这有助于。

Hope this helps.

(*),这并不意味着你不能忽视的确切的命名空间的XPath。例如,您可以匹配

(*) This doesn't mean you can't ignore the exact namespace in your XPath. For example, you could match

/*[local-name()='product']

但是,这是一种变通方法,并说明你仍然必须处理一个命名空间的presence莫名其妙地或其他。

But that's a workaround and illustrates that you still have to deal with the presence of a namespace somehow or other.

这篇关于如何使用NamspaceManager解析在C#中的XML,XML具有被命名空间的元素级别定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:47