How can I add InnerXml without it being modified in any way?

℡╲_俬逩灬. 提交于 2020-01-14 03:00:07

问题


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.

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>

So: Is there a way to set the InnerXml without it being modified?


回答1:


You can create the a XmlElement the same way you create the root element, and specify the InnerText of that element.

Option 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);

Option 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);

Resulting XML:

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

If you use root.InnerXml = "<a>b</a>"; instead of creating the XmlElement from the XmlDocument the resulting XML is:

Option 1:

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

Option 2:

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


来源:https://stackoverflow.com/questions/14841517/how-can-i-add-innerxml-without-it-being-modified-in-any-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!