1

毎回指定する必要も、取得する必要もなく、XMLをXML-with-xmlnsに追加する簡単な方法を見つけようとしています。xmlns=""xmlns

XDocument私は両方を試しましXmlDocumentたが、簡単な方法を見つけることができませんでした。私が得た最も近いものはこれをすることでした:

XmlDocument xml = new XmlDocument();

XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);
XmlElement root = xml.CreateElement("root", @"http://example.com");
xml.AppendChild(root);

root.InnerXml = "<a>b</a>";

しかし、私が得るものはこれです:

<root xmlns="http://example.com">
  <a xmlns="">b</a>
</root>

だから:InnerXmlそれを変更せずに設定する方法はありますか?

4

1 に答える 1

2

要素を作成するa XmlElementのと同じ方法で作成し、そのroot要素の を指定できますInnerText

オプション1:

string ns = @"http://example.com";

XmlDocument xml = new XmlDocument();

XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);

XmlElement root = xml.CreateElement("root", ns);
xml.AppendChild(root);

XmlElement a = xml.CreateElement("a", ns);
a.InnerText = "b";
root.AppendChild(a);

オプション 2:

XmlDocument xml = new XmlDocument();

XmlNode docNode = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
xml.AppendChild(docNode);

XmlElement root = xml.CreateElement("root");
xml.AppendChild(root);
root.SetAttribute("xmlns", @"http://example.com");

XmlElement a = xml.CreateElement("a");
a.InnerText = "b";
root.AppendChild(a);

結果の XML:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://example.com">
    <a>b</a>
</root>

結果の XMLからroot.InnerXml = "<a>b</a>";を作成する代わりに使用すると、次のようになります。XmlElementXmlDocument

オプション1:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://example.com">
    <a xmlns="">b</a>
</root>

オプション 2:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://example.com">
    <a xmlns="http://example.com">b</a>
</root>
于 2013-02-12T20:55:42.040 に答える