Dave Xu
Dave Xu

Reputation: 147

(C#) For xml with ":", already used XNamespace but still cannot finish parsing

Here is my XML content:

<app:DocItem Name="hello" ItemId="00000000-0000-0000-0000-000000000000" xmlns:app="xxxx">
    <app:Data>
        <cccc xmlns="yyyy" SchemaWriteVersion="1">
            <Key mClass="Tag">
                <SId Namespace="abc" ElementName="VP" />
            </Key>
            <Dictionary NId="116" Count="66">
                <Item>
                    <Key TId="7" Name="TemporaryDoNotUse" />
                    <Value Signature="....">
                    </Value>
                </Item>
            </Dictionary>
        </cccc>
    </app:Data>
</app:DocItem>

And here is what I'm trying in C# function:

    public static string GetVoicePolicy(string xmlStr)
    {
        XDocument xdoc = XDocument.Parse(xmlStr);

        StringBuilder result = new StringBuilder();

        XNamespace app = "app";
        XName n2 = app + "DocItem";
        XName n3 = app + "Data";

        XElement l2 = xdoc.Element(n2); //<<--------------------Line X
        XElement l3 = l2.Element(n3);
        XElement l4 = l3.Element("cccc");
        XElement l5 = l4.Element("Dictionary");
    ....
    }

I know for string with character ":", I cannot directly use "app:DocItem", but after using XNamespace, I still get "l2 == null" at "Line X" after it executed.

I can see content of xdoc which is correct, but l2 is just nothing. Did I miss anything?

Thanks!

Upvotes: 0

Views: 38

Answers (1)

Matti Virkkunen
Matti Virkkunen

Reputation: 65156

If you really have

xmlns:app="xxxx"

Then you'll want

XNamespace app = "xxxx";

The name app is not the name of the namespace, it's just a local prefix used in that particular XML file. It could even change every time.

Upvotes: 2

Related Questions