【问题标题】:How can I add InnerXml without it being modified in any way?如何在不以任何方式修改的情况下添加 InnerXml?
【发布时间】:2013-02-12 20:47:42
【问题描述】:

我正在尝试找到一种简单的方法来将 XML 添加到带有 xmlns 的 XML 中,而无需每次都指定 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 = "<a>b</a>";

但我得到的是:

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

那么:有没有办法在不修改InnerXml 的情况下设置它?

【问题讨论】:

  • xmlns="" 是因为您要添加来自不同命名空间的元素。将它们添加到父元素的命名空间,你不应该看到 xmlns="" 部分
  • 正如我所写 - 我试图 not 必须在每个节点中指定命名空间。
  • 只从父级获取 if,无需硬编码
  • xml 元素的身份包括它们的名称和命名空间。你看到的是 XmlDocument 试图保留你传递的身份,它不是在编造东西
  • 感谢您的意见。但问题很清楚,所以我不会争论。

标签: c# .net xml xml-namespaces


【解决方案1】:

您可以像创建root 元素一样创建a 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:

<?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;"; 而不是从XmlDocument 创建XmlElement,则生成的XML 为:

选项 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>

【讨论】:

  • 正如我所写 - 我试图 not 必须在每个节点中指定命名空间。
  • @ispiro 它不会将命名空间添加到每个节点,但为了避免拥有多个 xmlns 属性,您需要在创建它们时指定它们在同一个命名空间中。我知道必须为您创建的每个 XmlElement 一遍又一遍地指定命名空间是相当烦人的,但是要获得您想要的 XML,这就是您需要做的。
  • 我认为所建议的是解决方案。如果您这样做,命名空间将仅位于根节点。它在子节点中显示为xmlns="" 的原因是因为它在与父节点不同的命名空间
  • @SamHolder & JG in SD - 我明白这一点。但正如我所写 - 我正在尝试 not 必须在每个节点中指定命名空间。看看你的代码。它确实
  • 非常感谢您的坚持。您的解决方案完美运行(即使使用root.InnerXml = "&lt;a&gt;b&lt;/a&gt;";)。
猜你喜欢
  • 2013-04-23
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 2023-04-01
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多