我得到了这样的 XML:
<Type>
<Connections>
<Conn ServerName="serv1" DataBase="Persons" User="admin" Pass="123"/>
<Conn ServerName="serv2" DataBase="Type123" User="admin" Pass="123"/>
</Connections>
<UDLFiles />
</Type>
所以我这样加载xml
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
并且我给出了 ServerName、DataBase、User 和 Pass 的组合。
如果我已经将此组合添加为 <Conn>
,如何 checkin XML (那是 4 个属性)如果我还没有添加它,如何添加它?
最佳答案
另一种选择(如果您使用的是 .Net 3.5 或更高版本)是跳过 XmlDocument 并使用 LINQ to XML,在我看来,这会产生更清晰的代码:
// Load the XML from file
XElement docElem = XElement.Load(path);
// Get the Connections element. This code assumes there will always be exactly one.
XElement connectionsElem = docElem.Elements("Connections").Single();
// Check if there is already a Conn element with the required attribute value combination
if (!connectionsElem.Elements("Conn").Any(connElem =>
(string)connElem.Attribute("ServerName") == serverName &&
(string)connElem.Attribute("DataBase") == dataBase &&
(string)connElem.Attribute("User") == user &&
(string)connElem.Attribute("Pass") == pass)) {
// Otherwise add such a Conn element
connectionsElem.AddFirst(
new XElement("Conn",
new XAttribute("ServerName", serverName),
new XAttribute("DataBase", dataBase),
new XAttribute("User", user),
new XAttribute("Pass", pass)
)
);
}
// Write the XML to file again.
docElem.Save(path);
关于c# - 如果需要,如何搜索和更改 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5064317/