簡體   English   中英

具有XDocument和xsi:schemaLocation的C#

[英]C# with XDocument and xsi:schemaLocation

我想創建以下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嗎?

您需要對所有元素使用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")
                     )
         )
     ); 

點網演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM