使用c#重命名XML根节点
本文关键字:根节点 XML 重命名 使用 | 更新日期: 2023-09-27 18:07:36
我使用下面的代码来更改根节点名称。但这对我不起作用。请帮我做这件事。我的部分代码如下:
XmlNode PackageListNode = hst_doc.SelectSingleNode("NewDataSet");
XmlNodeList PackageNodeList = PackageListNode.SelectNodes("Table5");
hst_doc.DocumentElement.Name.Replace("NewDataSet", "rows");
参考此链接:
http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx遵循以下代码:
XmlDocument objDoc = new XmlDocument();
objDoc.LoadXml(str);
XmlDocument objNewDoc = new XmlDocument();
XmlElement objNewRoot = objNewDoc.CreateElement("MasterList");
objNewDoc.AppendChild(objNewRoot);
objNewRoot.InnerXml = objDoc.DocumentElement.InnerXml;
String xml = docNew.OuterXml;
我相信你没有调用Save()方法更改后尝试下面的代码
XmlNode PackageListNode = hst_doc.SelectSingleNode("NewDataSet");
XmlNodeList PackageNodeList = PackageListNode.SelectNodes("Table5");
hst_doc.DocumentElement.Name.Replace("NewDataSet", "rows");
hst_doc.Save("filename");
试试这个
// Obtain a document; this method is implemented in
// The Quintessential Program to Create a DOM Document from an XML File
Document doc = parseXmlFile("infilename.xml", false);
// Obtain the root element
Element element = doc.getDocumentElement();
// Create an element with the new name
Element element2 = doc.createElement("newname");
// Copy the attributes to the new element
NamedNodeMap attrs = element.getAttributes();
for (int i=0; i<attrs.getLength(); i++) {
Attr attr2 = (Attr)doc.importNode(attrs.item(i), true);
element2.getAttributes().setNamedItem(attr2);
}
// Move all the children
while (element.hasChildNodes()) {
element2.appendChild(element.getFirstChild());
}
// Replace the old node with the new node
element.getParentNode().replaceChild(element2, element);
Or Try This
XDocument doc = XDocument.Load("input.xml");
doc.Root.Name = "program";
doc.Save("output.xml");