【问题标题】:C# with XDocument and xsi:schemaLocation带有 XDocument 和 xsi:schemaLocation 的 C#
【发布时间】:2015-06-26 06:55:34
【问题描述】:

我想创建以下 XML。

<?xml version="1.0" encoding="utf-8"?>
<MyNode xsi:schemaLocation="https://MyScheme.com/v1-0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://MyScheme.com/v1-0 Sscheme.xsd">
  <MyInfo>
    <MyNumber>string1</MyNumber>
    <MyName>string2</MyName>
    <MyAddress>string3</MyAddress>
  </MyInfo>
  <MyInfo2>
    <FirstName>string4</FirstName>
  </MyInfo2>
</MyNode>

我正在使用此代码。

    XNamespace xmlns = "https://MyScheme.com/v1-0 Sscheme.xsd";
    XNamespace xsi = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
    XNamespace schemaLocation = XNamespace.Get("https://MyScheme.com/v1-0");

    XDocument xmlDocument = new XDocument(
         new XElement(xmlns + "MyNode",
             new XAttribute(xsi + "schemaLocation", schemaLocation),
             new XAttribute(XNamespace.Xmlns + "xsi", xsi),
             new XElement("MyInfo",
                 new XElement("MyNumber", "string1"),
                 new XElement("MyName", "string2"),
                 new XElement("MyAddress", "string3")
                 ),
                 new XElement("MyInfo2",
                     new XElement("FirstName", "string4")
                     )
         )
     );
    xmlDocument.Save("C:\\MyXml.xml");

但是,我在标签 MyInfo 和 MyInfo2 中得到了 xmlns=""。

有人可以帮我创建正确的 XML 吗?

【问题讨论】:

    标签: c# xml linq-to-xml linq-to-xsd xnamespace


    【解决方案1】:

    您需要对所有元素使用xmlns XNamespace,因为这是默认命名空间,并且在根级元素中声明。请注意,后代元素隐式继承祖先默认命名空间,除非另有说明:

    XDocument xmlDocument = new XDocument(
             new XElement(xmlns + "MyNode",
                 new XAttribute(xsi + "schemaLocation", schemaLocation),
                 new XAttribute(XNamespace.Xmlns + "xsi", xsi),
                 new XElement(xmlns+"MyInfo",
                     new XElement(xmlns+"MyNumber", "string1"),
                     new XElement(xmlns+"MyName", "string2"),
                     new XElement(xmlns+"MyAddress", "string3")
                     ),
                     new XElement(xmlns+"MyInfo2",
                         new XElement(xmlns+"FirstName", "string4")
                         )
             )
         ); 
    

    Dotnetfiddle Demo

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-05
    • 2010-11-27
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多