开发者

Traversing complex XML document in C# with XLinq

So I want to access the child element in a structure that looks like this:

<asdf:foobar attr="value">
    <child>...</child>
</asdf:foobar>

I forget what the asdf is called, but it is what's causing the problem. My normal method of traversing in XLinq doesn't work:

xElem child = xDoc.Element("foobar");

Sets child to null because it claims there is no element foobar, and

xElem child = xDoc.Element("asdf:foobar");

Doesn't work because the compiler whines about the semicolon.

All help is appreciated, and thanks in advance!

UPDATE:

I've been working on a reproduction of this as an example (since I can't show you the 开发者_运维技巧actual code). My test code:

        Console.WriteLine("BEGIN TEST");

        const string MY_SCHEMA = "http://www.example.com/whatever";

        XElement xTest =
        new XElement("{" + MY_SCHEMA + "}base",
            new XAttribute("{" + XML_STANDARD + "}boofar", MY_SCHEMA),
            new XAttribute("attr1", "val"),
            new XElement("{" + MY_SCHEMA + "}asdf", "ghjkl")
        );

        result.Text = xTest.ToString();

        XElement xOps2 = xTest.Element(XName.Get("asdf", MY_SCHEMA));
        XElement xSubOps2;

        if (xOps2 == null)
        {
            MessageBox.Show("Failure.");
        }
        else
        {
            xSubOps2 = xOps2.Element(XName.Get("asdf", MY_SCHEMA));
            MessageBox.Show(xSubOps2.ToString());
        }

        Console.WriteLine("END TEST");

        MessageBox.Show("END TEST");

This displays the XML that I want:

<boofar:base xmlns:boofar="http://www.example.com/whatever" attr1="val">
  <boofar:asdf>ghjkl</boofar:asdf>
</boofar:base>

And everything is working great. Thanks all!


Unfortunately the implicit conversion from string to XName does not parse out the namespace. You need to do this:

XName.Get("foobar", "asdf");


Another way you can handle namespaces is by using the XNamespace class.

  XNamespace ns = "http://www.example.com/whatever";
  XElement child = new XElement(ns + "base");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜