2017-06-27 37 views
1

我建立一個XML文檔,我已經宣佈,在最高層的命名空間創建一個從字符串的XmlElement。C#沒有的xmlns =「」

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

在下面我想從一個字符串創建一個元素的appendChild一些任意的水平。我的目標是最終得到一個包含那個元素而沒有xmlns AT ALL的文檔。

這是最接近我gotten-

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

該代碼產生IN-

<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,因爲它是同根。

誰能告訴我建立與內單個命名空間的使用,其中一些元素存儲在模型中作爲一個字符串文件的慣用方法是什麼?

issue這幾乎是相同的礦除溶液具有僅提供所述子元件作爲字符串(在「新」的所有內容)的奢侈品。我需要整個元素。

+0

您可以將XML字符串加載到XmlDocument中,然後獲取子節點並將其添加到現有的XML文檔中。 –

+0

我試圖從loadXML的創建的文檔添加我的元素,但它不喜歡跨文檔的appendChild。如果您建議將整個文檔作爲不正確的字符串,我只有一些元素。 –

回答

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

凡你有XDOC的XDocument,我一直在做處理很多與XmlDocument的文檔。我可以以某種方式將xChild添加到doc中嗎? –