【问题标题】:C# Create XmlElement from string without xmlns=""C# 从没有 xmlns="" 的字符串创建 XmlElement
【发布时间】:2017-06-27 17:13:27
【问题描述】:

我正在构建一个 xml 文档,并且我已经在最顶部声明​​了命名空间。

<Root xmlns="http://www.omg.org/space/xtce" xmlns:xtce="http://www.omg.org/space/xtce" ...>

在下面的某个任意级别,我想 AppendChild 使用从字符串创建的元素。我的目标是最终得到一个包含该元素而完全没有 xmlns 的文档。

这是我得到的最接近的-

string someElementStr = "<SomeElement name="foo"><SubElement name="bar" /></SomeElement>";
XmlDocumentFragment node = doc.CreateDocumentFragment();
node.InnerXml = someElementStr;
someXmlNodeWithinDoc.AppendChild(node);

这段代码导致-

<SomeElement name="foo" xmlns=""> <SubElement name="bar" /> </SomeElement> 在最终文档中。

当我不必从字符串转到 XML 时,我使用不同的构造-

XmlElement elem = doc.CreateElement("SomeElement", "http://www.omg.org/space/xtce");
elem.SetAttribute("name","foo");
someXmlNodeWithinDoc.AppendChild(elem);

这正是我想要的。

<SomeElement name="foo"> </SomeElement>

我想在我当前的解决方案中做一些事情 node.setNamespace("http://www.omg.org/space/xtce") 则文档将省略 xmlns,因为它与 root 相同。

谁能告诉我用单一命名空间构建文档的惯用方式,其中一些元素作为字符串存储在模型中?

这个issue 几乎与我的相同,只是该解决方案仅提供子元素作为字符串(“新”下的所有内容)。我需要整个元素。

【问题讨论】:

  • 您可以将 XML 字符串加载到 XmlDocument,然后获取子节点并将其添加到现有 XML 文档中。
  • 我尝试从使用 LoadXml 创建的文档中添加我的元素,但它不喜欢跨文档 AppendChild。如果您建议我将整个文档作为一个不正确的字符串,我只有一些元素。

标签: c# xml c#-4.0 xml-namespaces


【解决方案1】:
string xmlRoot = "<Root xmlns=\"http://www.omg.org/space/xtce\"></Root>";
string xmlChild = "<SomeElement name=\"foo\"><SubElement name = \"bar\"/></SomeElement >";
XDocument xDoc = XDocument.Parse(xmlRoot);
XDocument xChild = XDocument.Parse(xmlChild);            
xChild.Root.Name = xDoc.Root.GetDefaultNamespace() + xChild.Root.Name.LocalName;
foreach (XElement xChild2 in xChild.Root.Nodes())
{
  xChild2.Name = xDoc.Root.GetDefaultNamespace() + xChild2.Name.LocalName;
}
xDoc.Root.Add(xChild.Root);
string xmlFinal = xDoc.ToString();

【讨论】:

  • 在你有 XDocument xDoc 的地方,我一直在使用 XmlDocument doc 进行大量处理。我可以以某种方式将 xChild 添加到文档中吗?
【解决方案2】:

这是我最终得到的解决方案。我没有使用@shop350 解决方案,因为我不想使用 XDocument、XElement...不过感谢您的反馈!

// create a fragment which I am going to build my element based on text.

XmlDocumentFragment frag = doc.CreateDocumentFragment();

// here I wrap my desired element in another element "dc" for don't care that has the namespace declaration.
string str = "";
str = "<dc xmlns=\"" + xtceNamespace + "\" ><Parameter name=\"paramA\" parameterTypeRef=\"paramAType\"><AliasSet><Alias nameSpace=\"ID\" alias=\"0001\"/></AliasSet></Parameter></dc>";

// set the xml for the fragment (same namespace as doc)
frag.InnerXml = str;

// let someXmlNodeWithinDoc be of type XmlNode which I determined based on XPath search.
// Here I attach the child element "Parameter" to the XmlNode directly effectively dropping the element <dc>
someXmlNodeWithinDoc.AppendChild(frag.FirstChild.FirstChild);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2013-09-29
    • 2021-12-22
    • 2018-05-25
    相关资源
    最近更新 更多