从XElement创建带有命名空间和模式的XML

12

一个啰嗦的问题 - 请耐心等待!

我想以编程方式创建一个带有命名空间和架构的 XML 文档。类似于

<myroot 
    xmlns="http://www.someurl.com/ns/myroot" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.someurl.com/ns/myroot http://www.someurl.com/xml/schemas/myschema.xsd">

    <sometag>somecontent</sometag>

</myroot>

我正在使用非常出色的新LINQ工具(对我来说是新的),希望使用XElement完成上述操作。

我的对象上有一个ToXElement()方法:

  public XElement ToXElement()
  {
     XNamespace xnsp = "http://www.someurl.com/ns/myroot";

     XElement xe = new XElement(
        xnsp + "myroot",
           new XElement(xnsp + "sometag", "somecontent")
        );

     return xe;
  }

这使我正确地获得了命名空间,因此:

<myroot xmlns="http://www.someurl.com/ns/myroot">
   <sometag>somecontent</sometag>
</myroot>

我的问题是:如何添加schema的xmlns:xsi和xsi:schemaLocation属性?

(顺便说一下,我不能使用简单的XAttributes,因为在属性名中使用冒号“:”会导致错误...)

还是我需要使用XDocument或其他LINQ类吗?

谢谢...

2个回答

7
从这篇文章来看,似乎您需要新建多个XNamespace,向根属性添加一个属性,然后使用两个XNamespace。
// The http://www.adventure-works.com namespace is forced to be the default namespace.
XNamespace aw = "http://www.adventure-works.com";
XNamespace fc = "www.fourthcoffee.com";
XElement root = new XElement(aw + "Root",
    new XAttribute("xmlns", "http://www.adventure-works.com"),
///////////  I say, check out this line.
    new XAttribute(XNamespace.Xmlns + "fc", "www.fourthcoffee.com"),
///////////
    new XElement(fc + "Child",
        new XElement(aw + "DifferentChild", "other content")
    ),
    new XElement(aw + "Child2", "c2 content"),
    new XElement(fc + "Child3", "c3 content")
);
Console.WriteLine(root);

这里有一个关于如何进行模式位置的论坛帖子

7

感谢David B - 我不太确定我是否完全理解了这个代码,但这段代码给我了我需要的东西...

  public XElement ToXElement()
  {
     const string ns = "http://www.someurl.com/ns/myroot";
     const string w3 = "http://wwww.w3.org/2001/XMLSchema-instance";
     const string schema_location = "http://www.someurl.com/ns/myroot http://www.someurl.com/xml/schemas/myschema.xsd";

     XNamespace xnsp = ns;
     XNamespace w3nsp = w3;

     XElement xe = new XElement(xnsp + "myroot",
           new XAttribute(XNamespace.Xmlns + "xsi", w3),
           new XAttribute(w3nsp + "schemaLocation", schema_location),
           new XElement(xnsp + "sometag", "somecontent")
        );

     return xe;
  }

似乎将命名空间和字符串连接起来,例如
w3nsp + "schemaLocation"
,会在生成的XML中产生一个名为
xsi:schemaLocation
的属性,这正是我需要的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接