我试图找到的简单的方式来增加XML到XML-与-的xmlns没有得到的的xmlns =
,也有指定的xmlns
每次
I'm trying to find a simple way to add XML to XML-with-xmlns without getting the xmlns=""
nor having to specify the xmlns
every time.
我都尝试的XDocument
和的XmlDocument
,但无法找到一个简单的方法。我最近在做这样的:
I tried both XDocument
and XmlDocument
but couldn’t find a simple way. The closest I got was doing this:
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>";
但我得到的是这样的:
But what I get is this:
<root xmlns="http://example.com">
<a xmlns="">b</a>
</root>
所以:有没有一种方法来设置 InnerXml
没有它被修改
推荐答案
您可以创建 A
的XmlElement
的创建同样的方法根
元素,并指定的InnerText
的元素。
You can create the a
XmlElement
the same way you create the root
element, and specify the InnerText
of that element.
选项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:
Resulting XML:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://example.com">
<a>b</a>
</root>
如果您使用 root.InnerXml =&LT; A&GT; B&LT; / A&gt;中;
而不是创建的XmlElement
从的XmlDocument
生成的XML是:
If you use root.InnerXml = "<a>b</a>";
instead of creating the XmlElement
from the XmlDocument
the resulting XML is:
选项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>
相关推荐
最新文章