代码之家  ›  专栏  ›  技术社区  ›  SAL

从XElement创建具有名称空间和模式的XML

  •  12
  • SAL  · 技术社区  · 16 年前

    一个冗长的问题——请容忍我!

    <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 回复  |  直到 16 年前
        1
  •  7
  •   Amy B    16 年前

    由此 article

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

        2
  •  7
  •   SAL    16 年前

    感谢大卫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"
    给出一个名为
    xsi:schemaLocation
    在生成的XML中,这正是我所需要的。