如何通过使用linq到xml在xml文件中添加新标签,我希望新标签是第一个标签
<?xml version="1.0" encoding="utf-8"?>
<settings>
<Device>
<username>fooo</username>
<AgentName>fooo</AgentName>
<password>fooo</password>
</Device>
<Device>
<username>fooo1</username>
<AgentName>fooo1</AgentName>
<password>fooo1</password>
</Device>
</settings>
现在我想添加一个新标签来制作像这样的文件
<settings>
<IncommingConfig>
<ip>10.100.101.18</ip>
<port>5060</port>
</IncommingConfig>
<Device>
<username>fooo</username>
<AgentName>fooo</AgentName>
<password>fooo</password>
</Device>
<Device>
<username>fooo1</username>
<AgentName>fooo1</AgentName>
<password>fooo1</password>
</Device>
</settings>
答案 0 :(得分:3)
使用XContainer.AddFirst
很容易,它会将给定值添加为第一个子项:
XDocument doc = XDocument.Load("data.xml");
doc.Root.AddFirst(new XElement("IncomingConfig", // Fixed typo in name
new XElement("ip", ipAddress),
new XElement("port", port)));
doc.Save("output.xml");
答案 1 :(得分:2)
XDocument xmldoc = XDocument.Load(Server.MapPath("...."));
XElement parentXElement = xmldoc.XPathSelectElement("settings");
XElement newXElement = new XElement("IncommingConfig");
..
parentXElement.AddFirst(newXElement);