2008-12-02 111 views
12

一个长期问题 - 请耐心等待!使用XElement中的名称空间和模式创建XML

我想以编程方式创建一个名称空间和模式的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> 

我的问题:我怎么能添加架构的xmlns :xsi和xsi:schemaLocation属性?

(顺便说一句,我不能用简单的XAtttributes,因为我得到一个错误,用冒号“:”在属性名...)

或者我需要使用一个XDocument或其他一些LINQ类?

谢谢...

回答

7

从这个article,它看起来像你新的多于一个的XNamespace,在根添加属性,然后去城里与两个XNamespaces。

// 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); 

这是一个forum post显示如何做schemalocation。

7

感谢David乙 - 我不能肯定我明白这一切,但是这个代码让我什么,我需要......

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
的属性,这正是我所需要的。