2010-08-30 140 views
6

我已經XML存儲在字符串變量:更改的XML根元素名稱

<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList> 

在這裏我要XML標籤<ItemMasterList>更改爲<Masterlist>。我怎樣才能做到這一點?

+1

你應該張貼了一下你正在使用的代碼,因爲沒有做到這一點的方法不止一種。 – 2010-08-30 14:28:01

回答

10

System.Xml.XmlDocument和相同命名空間中的關聯類將在這裏證明對你非常寶貴。

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(yourString); 
XmlDocument docNew = new XmlDocument(); 
XmlElement newRoot = docNew.CreateElement("MasterList"); 
docNew.AppendChild(newRoot); 
newRoot.InnerXml = doc.DocumentElement.InnerXml; 
String xml = docNew.OuterXml; 
+0

可否請您提供我的代碼。 – Pradeep 2010-08-30 14:28:03

+1

修改爲包含示例。 – 2010-08-30 14:31:51

+2

-1 - 只讀屬性。 – 2010-08-30 14:32:46

6

您可以使用LINQ to XML解析XML字符串,創建一個新的根,原根的子元素和屬性添加到新根:

XDocument doc = XDocument.Parse("<ItemMasterList>...</ItemMasterList>"); 

XDocument result = new XDocument(
    new XElement("Masterlist", doc.Root.Attributes(), doc.Root.Nodes())); 
+0

+1,保持根的屬性完好 – Blorgbeard 2012-08-05 20:42:40

0

使用XmlDocument方式,你能做到這一點,如下所示(並保持完好樹):

XmlDocument oldDoc = new XmlDocument(); 
oldDoc.LoadXml("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>"); 
XmlNode node = oldDoc.SelectSingleNode("ItemMasterList"); 

XmlDocument newDoc = new XmlDocument(); 
XmlElement ele = newDoc.CreateElement("MasterList"); 
ele.InnerXml = node.InnerXml; 

如果你現在使用ele.OuterXml是將返回:(您只需字符串,否則我們ËXmlDocument.AppendChild(ele),你將能夠使用XmlDocument對象多一些)

<MasterList> 
    <ItemMaster> 
    <fpartno>xxx</fpartno> 
    <frev>000</frev> 
    <fac>Default</fac> 
    </ItemMaster> 
</MasterList> 
0

正如指出的意志,我們可以這樣做的,但對於其中InnerXml等於OuterXml情況下,以下解決方案將制定出:

// Create a new Xml doc object with root node as "NewRootNode" and 
// copy the inner content from old doc object using the LastChild. 
        XmlDocument docNew = new XmlDocument(); 
        XmlElement newRoot = docNew.CreateElement("NewRootNode"); 
        docNew.AppendChild(newRoot); 
// The below line solves the InnerXml equals the OuterXml Problem 
        newRoot.InnerXml = oldDoc.LastChild.InnerXml; 
        string xmlText = docNew.OuterXml; 
6

我知道我有點晚了,但只需要添加這個答案,因爲似乎沒有人知道這件事。

XDocument doc = XDocument.Parse("<ItemMasterList><ItemMaster><fpartno>xxx</fpartno><frev>000</frev><fac>Default</fac></ItemMaster></ItemMasterList>");  
doc.Root.Name = "MasterList"; 

哪個返回如下:

<MasterList> 
    <ItemMaster> 
    <fpartno>xxx</fpartno> 
    <frev>000</frev> 
    <fac>Default</fac> 
    </ItemMaster> 
</MasterList> 
+0

更簡單,完全重命名,保持一切完好無損。 – Horia 2018-01-15 14:57:38