2

デフォルトの名前空間をルートに追加しようと何度か試みましたが、その子にも名前空間が追加されます。名前空間を既存の XDocument に追加したいと考えています。

私のコードは試みます。

// add default namespace - attempt 1
XNamespace xmlns = "http://www.myschema/schema.xsd";
xDocument.Root.Name = xmlns + xDocument.Root.Name.LocalName;

// add default namespace - attempt 2
XNamespace MyNS = "http://www.myschema/schema.xsd";
xDocument.Element("testFile").Name = MyNS.GetName("testFile");

XML;

<testFile version="1" xmlns="http://www.myschema/schema.xsd">
  <testResults xmlns="">  <!-- *** Unwanted Attribute *** -->
    <result resultID="abcdefgh" comment="blah blah blah blah">
  </testResults>
</testFile>

testResults に xmlns 名前空間属性が付加されている理由を知りたいですか?

テスト対象のテスト C# コードを次に示します。

XDocument xDocument = new XDocument(
    new XElement("testFile",
        new XAttribute("version", "1"),
        new XElement("testResults",
            new XElement("result",
                new XAttribute("resultID", "abcdefgh"),
                new XAttribute("comment", "blah blah blah blah")
        ))));
4

3 に答える 3

3
XNamespace ns = "http://www.myschema/schema.xsd";
XDocument xDocument = new XDocument(
new XElement(ns + "testFile",
    new XAttribute("version", "1"),
    new XElement(ns + "testResults",
        new XElement(ns + "result",
            new XAttribute("resultID", "abcdefgh"),
            new XAttribute("comment", "blah blah blah blah")
    ))));
于 2012-11-15T19:26:59.397 に答える
1

次のコード:

var xDocument = new XmlDocument();
var element1 = xDocument.CreateElement("testFile", "http://www.myschema/schema.xsd");
element1.SetAttribute("version", "1");
xDocument.AppendChild(element1);

var element2 = xDocument.CreateElement("testResults", "http://www.myschema/schema.xsd");
element1.AppendChild(element2);

var element3 = xDocument.CreateElement("result", "http://www.myschema/schema.xsd");
element3.SetAttribute("resultID", "abcdefgh");
element3.SetAttribute("comment", "blah blah blah blah");
element2.AppendChild(element3);

次のxmlファイルを生成します。

<testFile version="1" xmlns="http://www.myschema/schema.xsd">
  <testResults>
    <result resultID="abcdefgh" comment="blah blah blah blah" /> 
  </testResults>
</testFile>
于 2012-11-15T16:40:28.343 に答える
1

「名前空間を XDocument に追加する」ことはできません。ドキュメントには名前空間がありません要素と属性の名前には名前空間があります。

ドキュメント内のすべての要素の名前空間を変更する必要があり、場合によってはいくつかの属性も変更する必要があります。

于 2012-11-15T16:46:09.343 に答える