我喜欢你看看: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
你是否也试图在我提供的链接中应用这些例子? –