如何在不进行任何修改的情况下添加InnerXml?

我试图找到一种简单的方法来将XML添加到XML-with-xmlns而不必获取xmlns=""也不必每次都指定xmlns

我尝试了XDocumentXmlDocument但找不到简单的方法。 我得到的最接近的是这样做:

 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 = "b"; 

但我得到的是:

  b  

那么:有没有办法设置InnerXml而不进行修改?

您可以像创建root元素一样创建XmlElement ,并指定该元素的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:

   b  

如果你使用root.InnerXml = "b"; 而不是从XmlDocument创建XmlElement ,结果XML是:

选项1:

   b  

选项2:

   b