c# - 如果需要,如何搜索和更改 XML?

标签 c# xml

我得到了这样的 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/

相关文章:

java - 膨胀异常 : Binary XML file line #22: Error inflating class <unknown>

c# - 关于C#中线程的问题

c# - Find 和 FindAsync 之间的区别

sql - 如何使用 T-SQL 和 XQuery 从 XML 中进行选择

java - 没有互联网连接时,Spring schemaLocation 失败

xml - 在 Ruby 中使用多个 XSD 验证 XML

c# - 除非我切换选项卡,否则Toolstrip标签不会更新

c# - WindowsInstaller C# 控制台应用程序缺少库引用

c# - 异常 : When to use, 时序,整体使用

xml - 遍历一个 XML 文档的所有节点?