-1

以下のような XML ドキュメントを生成しようとしています。いくつかの解決策を試しましたが、名前空間を追加すると、ほとんどどこにでも名前空間があります

<FieldB xlmns="">BBBBB</FieldB>

これを取得する方法はありますか?

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<value attributeA="A" attributeB="B" xmlns:XXX="http://MyURLA" xmlns="http://MyURLB">
    <FieldA>AAAAA</FieldA>
    <FieldB>BBBBB</FieldB>
    <FieldB>BBBBB</FieldB>
    <status attributeC="C">
        <FieldC>ValueFieldC</FieldC>
    </status>
    <LastUpdate date="2011-02-11T10:00:56.350" login="testing"/>
    <XXX:Infos>
        <XXX:Info>
            <XXX:InfoA>false</XXX:InfoA>
            <XXX:InfoB>false</XXX:InfoB>
        </XXX:Info>
    </XXX:Infos>
</value>
4

2 に答える 2

2

XNamespace を使用できます。

public class Program
{
    static void Main()
    {
        XNamespace nsA = "http://MyURLA";
        XNamespace nsB = "http://MyURLB";
        var doc = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement(
                nsB + "value",
                new XAttribute(XNamespace.Xmlns + "XXXX", nsA),
                new XAttribute("attributeA", "A"),
                new XAttribute("attributeB", "B"),
                new XElement("FieldA", "AAAA"),
                new XElement("FieldA", "BBBB"),
                new XElement("FieldC", "CCCC"),
                new XElement(
                    "status", 
                    new XAttribute("attributeC", "C"),
                    new XElement("FieldC", "ValueFieldC")
                ),
                new XElement(
                    "LastUpdate", 
                    new XAttribute("date", DateTime.Now), 
                    new XAttribute("login", "testing")
                ),
                new XElement(
                    nsA + "Infos",
                    new XElement(nsA + "InfoA", false),
                    new XElement(nsA + "InfoB", false)
                )
            )
        );
        Console.WriteLine(doc.ToString());
    }
}
于 2012-09-25T11:48:56.307 に答える
1

I suspect the problem is that you're not putting FieldA, FieldB etc in the right namespace - you don't want to have an explicit namespace declaration in the XML, but the XML you've shown will actually have them in the namespace with URL http://MyURLB, due to the way defaults are inherited.

I suspect if you just use:

XNamespace nsB = "http://MyURLB";

var doc = ... {
    new XElement(nsB + "value", 
        ...
        new XElement(nsB + "FieldA", "AAAA");
        new XElement(nsB + "FieldB", "BBBB");
        new XElement(nsB + "FieldC", "CCCC");
        ...
    )
};

then it'll be fine. The FieldA (etc) elements won't have an explicit namespace reference, because they're in the same namespace as their parent element.

于 2012-09-25T12:51:16.467 に答える