我有這個 XML 結構:
<?xml version="1.0" ?>
<server xmlns="exampleServer">
<system-properties>
<property name="prop0" value="null"/>
<property name="prop1" value="true"/>
<property name="prop2" value="false"/>
</system-properties>
</server>
但我不知道如何添加具有兩個屬性的新“屬性”行。最好的方法是什么?我試過了:
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.DocumentElement;
string nameSpace = root.GetAttribute("xmlns");
XmlNode nn = doc.CreateNode(XmlNodeType.Attribute, "property",
nameSpace);
XmlAttribute attr = doc.CreateAttribute("name");
attr.Value = "prop3";
nn.AppendChild(attr);
attr = doc.CreateAttribute("value");
attr.Value = "value3";
nn.AppendChild(attr);
doc.AppendChild(nn);
doc.Save(path);
但出現錯誤“節點型別錯誤”。
uj5u.com熱心網友回復:
您遇到的例外是由您指定的事實引起的XmlNodeType.Attribute。你真正想要的是XmlNodeType.Element。
但是,如果您XmlDocument.CreateElement(String, String)改為使用,您將獲得一個XmlElement物件,該物件具有使添加屬性更容易的方法:
XmlDocument doc = new XmlDocument();
doc.Load(path);
// Create the new XML element and set attributes
string defaultNameSpace = doc.DocumentElement.GetAttribute("xmlns");
var propertyElement = doc.CreateElement("property", defaultNameSpace);
propertyElement.SetAttribute("name", "prop3");
propertyElement.SetAttribute("value", "value3");
// Find the element to append the new element to
var nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("ns", defaultNameSpace);
var sysPropNode = doc.SelectSingleNode("//ns:system-properties", nsMgr);
sysPropNode.AppendChild(propertyElement);
doc.Save(path);
有關示例,請參見此小提琴。
uj5u.com熱心網友回復:
最好使用LINQ to XML API。
它自 2007 年起在 .Net Framework 中可用。它更簡單、更強大。
C#
void Main()
{
const string inputFile = @"e:\Temp\Guest.xml";
const string outputFile = @"e:\Temp\Guest_new.xml";
XDocument xdoc = XDocument.Load(inputFile);
XNamespace ns = xdoc.Root.GetDefaultNamespace();
xdoc.Descendants(ns "system-properties").FirstOrDefault()
.Add(new XElement(ns "property",
new XAttribute("name", "prop3"),
new XAttribute("value", "true")));
xdoc.Save(outputFile);
}
輸出
<?xml version="1.0" encoding="utf-8"?>
<server xmlns="exampleServer">
<system-properties>
<property name="prop0" value="null" />
<property name="prop1" value="true" />
<property name="prop2" value="false" />
<property name="prop3" value="true" />
</system-properties>
</server>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/459331.html
