krolik1991
krolik1991

Reputation: 244

Get element from xml node C#

I have xml and I want to get the value of node . My XML looks:

<?xml version="1.0" encoding="UTF-8"?>
<jdf:root xmlns:jdf="xxxxxxxx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<jdf:header>

    <jdf:locale-code>xx</jdf:locale-code>
    <jdf:country-code>xx</jdf:country-code>
</jdf:header>
<app:data xmlns:app="xxxxxx">
    <app:EventOut xmlns:ns2="xxxxxxx">
        <app:eventId>xxx</app:eventId>
        <app:distributorId>xxx</app:distributorId>
        <app:distributionNetworkId>xxx</app:distributionNetworkId>
        <app:typology>xxx</app:typology>
        <app:targets>
            <app:target>
                ......
            </app:target>
            <app:target>
                .....
            </app:target>
        </app:targets>
        <app:object>
            <ns2:internalEventObject>
                <ns2:id>!!!!!!!!</ns2:id>
                <ns2:lang1>xxx</ns2:lang1>
            </ns2:internalEventObject>
        </app:object>
        ...
    </app:EventOut>
</app:data>

I just try:

    XmlDocument xml = new XmlDocument();
    xml.LoadXml(eventOutXml);

    var nsmgr = new XmlNamespaceManager(xml.NameTable);
    nsmgr.AddNamespace("ns2", "http://www.w3.org/1999/XSL/Transform");

    XmlNode anode = xml.SelectSingleNode("//ns2:id", nsmgr);

But it is not working.

In My XML I have few namespaces:jdf, app, ns2. Maybe I must add all these?

Upvotes: 0

Views: 5172

Answers (2)

Your xml was missing end tag . And the namespace you added in the code was different in the xml. I did those two changes to the xml and was able to get this working.

Updated xml:

<?xml version="1.0" encoding="UTF-8"?>
<jdf:root xmlns:jdf="xxxxxxxx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<jdf:header>
    <jdf:locale-code>xx</jdf:locale-code>
    <jdf:country-code>xx</jdf:country-code>
</jdf:header>
<app:data xmlns:app="xxxxxx">
    <app:EventOut xmlns:ns2="http://www.w3.org/1999/XSL/Transform">
        <app:eventId>xxx</app:eventId>
        <app:distributorId>xxx</app:distributorId>
        <app:distributionNetworkId>xxx</app:distributionNetworkId>
        <app:typology>xxx</app:typology>
        <app:targets>
            <app:target>
                ......
            </app:target>
            <app:target>
                .....
            </app:target>
        </app:targets>
        <app:object>
            <ns2:internalEventObject>
                <ns2:id>!!!!!!!!</ns2:id>
                <ns2:lang1>xxx</ns2:lang1>
            </ns2:internalEventObject>
        </app:object>
        ...
    </app:EventOut>
</app:data>
</jdf:root>

After your code, just use this to get the value.

var value = anode.InnerText; //!!!!!!!!

Let me know if this works!

Upvotes: 1

Just Do It
Just Do It

Reputation: 486

Write down the entire path for that node.

XmlNode anode = xml.SelectSingleNode("/ns2:internalEventObjects/ns2:id", nsmgr);

Upvotes: 1

Related Questions