我喜歡你看看:https://msdn.microsoft.com/en-us/library/ms162365(v=vs.110).aspx,https://msdn.microsoft.com/en-us/library/system.xml.xmlnode(v=vs.110).aspx和https://msdn.microsoft.com/en-us/library/system.xml.xmlnode.appendchild(v=vs.110).aspx
微軟文檔是這些類型的問題的重要來源。
加載XML
您可以通過串
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
,或者通過使用文件流做到這一點(你可以用你現在擁有的XDocument)
XmlDocument xmlDocument = new XmlDocument();
using(XmlReader xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
選擇節點
爲此,您可以使用XPath(http://www.w3schools.com/xsl/xpath_syntax.asp,至極返回的XmlNodeList
XmlNodeList categoryNodes = xmlDocument.SelectNodes("config//newsy//category");
創建一個新的元素
爲了創建ü可以使用createElement方法的新元素(還有其他方法可以創建屬性等請參閱Microsoft文檔)。
XmlNode newSource = xmlDocument.CreateElement("source");
XmlNode newSourceUrl = xmlDocument.CreateElement("url");
newSourceUrl.InnerText = "http://www.test.com";
newSource.AppendChild(newSourceUrl);
這將創建一個新的源元素和一個url元素。 url元素將被追加到源元素。
將它添加到一個類別
將它添加到一個類別節點。
if (categoryNodes != null && categoryNodes.Count > 0)
categoryNodes[0].AppendChild(newSource);
搜索您要附加孩子的節點。你也可以查看某個屬性,像這樣:
foreach (XmlNode node in categoryNodes)
{
if (string.Equals(node.Attributes["id"].Value.ToString(), "sport", StringComparison.OrdinalIgnoreCase))
node.AppendChild(newSource);
}
保存
保存的XmlDocument。將其保存到磁盤:
xmlDocument.Save(path);
新的XML
<?xml version="1.0"?>
<config>
<newsy>
<category id="sport">
<source>
<contelemname>cont</contelemname>
<refresh>3</refresh>
<url>http://sport.wp.pl/rss.xml</url>
</source>
<source>
<contelemname>cont</contelemname>
<refresh>5</refresh>
<url>http://moto.wp.pl/rss.xml</url>
</source>
<source>
<url>http://www.test.com</url>
</source>
</category>
</newsy>
</config>
我希望這有助於ü。
是的人,它看起來不像op試過 – meda
我試過了所有的東西... – Enteee
你是否也試圖在我提供的鏈接中應用這些例子? –