如何使用特定命名空间创建XElement?

Grz*_*ekO 9 .net c# xml linq-to-xml

我在LinqToXml中创建新元素时遇到问题.这是我的代码:

XNamespace xNam = "name"; 
XNamespace _schemaInstanceNamespace = @"http://www.w3.org/2001/XMLSchema-instance";

XElement orderElement = new XElement(xNam + "Example",
                  new XAttribute(XNamespace.Xmlns + "xsi", _schemaInstanceNamespace));
Run Code Online (Sandbox Code Playgroud)

我想得到这个:

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
Run Code Online (Sandbox Code Playgroud)

但在XML中我总是这样:

<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="name">
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Mar*_*nen 11

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">由于name未声明前缀,因此格式不正确.因此,使用XML API构建它是不可能的.您可以做的是构造以下命名空间格式良好的XML

<name:Example xmlns:name="http://example.com/name" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
Run Code Online (Sandbox Code Playgroud)

与代码

        //<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="http://example.com/name"></name:Example>

        XNamespace name = "http://example.com/name";
        XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

        XElement example = new XElement(name + "Example",
            new XAttribute(XNamespace.Xmlns + "name", name),
            new XAttribute(XNamespace.Xmlns + "xsi", xsi));

        Console.WriteLine(example);
Run Code Online (Sandbox Code Playgroud)

  • 我忘了写这个.命名空间名称在父节点中声明.创建xml之后,我总是在一些xml验证器上验证它. (2认同)