0

Hi can anybody help me out. I have a XML which contains my own namespace xmlns:NS . I need to select all the nodes which contains the namespace "NS". How can we do this using C#.net.

I tried like below:

XmlDocument doc=new XmlDocument();
doc.Load(Path);
XmlNodeList oNodeList=doc.GetElementByTagname("NS:Text");

Here i am getting all the nodes which have "NS:Text" namespace. But I need to select all the nodes like below:

XmlDocument doc=new XmlDocument();
doc.Load(Path);
XmlNodeList oNodeList=doc.GetElementByTagname("NS");

so that i can select all the nodes which contains namespace "NS". but this is not working. How can we achieve this?

Following is my XML format.

<xml 1.0 ?>
    <Root xmlns:NS="www.yembi.com">
        <NS:Entry Value="User">
            <table>
                <tr>
                    <td>
                        <NS:display type="Label" name="First Name">
                    </td>
                </tr>
                <tr>
                    <td>
                        <NS:Text type="Text">
                    </td>
                </tr>
                <tr>
                    <td>
                        <NS:Button Type="SubmitButton" name="submit">
                    </td>
                </tr>
            </table>
        </NS:Entry>
4

2 に答える 2

1

.net フレームワーク バージョン 3.5 以降を使用している場合は、LINQ to XML をお勧めします。

    XDocument doc = XDocument.Load(Path);

    XNamespace ns = "www.yembi.com";
    var result = doc.Root.Descendants()
                   .Where(p => p.GetPrefixOfNamespace(ns) == "NS");
于 2012-07-02T07:57:32.517 に答える
0

SelectNodesメソッドで XPath 式を使用できます。

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

XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("NS", "www.yembi.com");
XmlNodeList oNodeList = doc.SelectNodes("//NS:*", mgr);

XPath 式は、プレフィックス//NS:*を持つ任意の要素を選択します。NS

あなたの質問に関する 1 つの注意:NSは Xml ドキュメントの名前空間ではなく、単なる名前空間のプレフィックスです。www.yembi.comあなたの名前空間です。

プレフィックスは、名前空間をドキュメント内の識別子に接続する名前空間のローカル (ドキュメント内) プレースホルダーと考えることができます。XPath 関連のコードのプレースホルダーを簡単に変更して (たとえば、 にx)、NSドキュメントに を残したままでも、それが名前空間のままである限り、問題は解決しませんwww.yembi.com

于 2012-07-02T07:49:08.257 に答える