C#从字符串创建XmlElement而不用xmlns =“”

时间:2017-06-27 17:13:28

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

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

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

在下面的某个任意级别,我想在AppendChild中添加一个从字符串创建的元素。我的目标是最终得到一个文档,其中包含没有xmlns AT ALL的元素。

这是我最接近的 -

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几乎与我的相同,只不过解决方案只能将子元素作为字符串提供(一切都在“新”下)。我需要整个元素。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这是我最终解决的问题。我没有使用@ 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);