0

次の 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 を作成するのを手伝ってくれませんか?

4

1 に答える 1

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

于 2015-06-26T07:44:07.913 に答える