我有一个知名节点的XML文件,称之为Foo。
因此,在XML文件的某个地方,我有一个看起来像这样的框架:
<Foo atr1="value1"/>
我想将其更改为:
<Foo atr1="value1"/>
<MyElement .......>
<MoreMystuff>
</MoreMystuff>
</MyElement>
然后需要将其写回磁盘上的相同文件。
这样做有什么好方法?
答案 0 :(得分:0)
如果我没有按照XML标准弄错,那么你的代码就只有一个根元素
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root><Foo atr1=\"value1\"/></root>");
/// or load from file as you want
//doc.Load("pathTOfile.xml")
XmlElement root = doc.DocumentElement;
XmlElement elem = doc.CreateElement("MyElement");
elem.Attributes.Append(doc.CreateAttribute("atrib"));
// Change the value of the first attribute.
elem.SetAttribute("atrib", "val");
XmlElement MoreStyffElem = doc.CreateElement("MoreStuff");
elem.AppendChild(MoreStyffElem);
doc.FirstChild.AppendChild(elem);
Console.WriteLine("Display the modified XML...");
Console.WriteLine(doc.InnerXml);
//or save to file
//doc.Save("theSameFileName.xml")
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root><Foo atr1=\"value1\"/></root>");
/// or load from file as you want
//doc.Load("pathTOfile.xml")
XmlElement root = doc.DocumentElement;
XmlElement elem = doc.CreateElement("MyElement");
elem.Attributes.Append(doc.CreateAttribute("atrib"));
// Change the value of the first attribute.
elem.SetAttribute("atrib", "val");
XmlElement MoreStyffElem = doc.CreateElement("MoreStuff");
elem.AppendChild(MoreStyffElem);
doc.FirstChild.AppendChild(elem);
Console.WriteLine("Display the modified XML...");
Console.WriteLine(doc.InnerXml);
//or save to file
//doc.Save("theSameFileName.xml")
此链接也必须对您有用
http://msdn.microsoft.com/en-en/library/y3y47afh.aspx