0

我有以下 xml 文件

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfParams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Params Key="Domain" Value="User123">
    <Variable>
      <Name>Domain</Name>
      <Type>String</Type>
      <Value>User123</Value>
    </Variable>
  </Params>
  <Params Key="Password" Value="Password123">
    <Variable>
      <Name>Password</Name>
      <Type>String</Type>
      <Value>Password123</Value>
    </Variable>
  </Params>
  <Params Key="Username" Value="Domain123">
    <Variable>
      <Name>Username</Name>
      <Type>String</Type>
      <Value>Domain123</Value>
    </Variable>
  </Params>
</ArrayOfParams>

我想将密码从更改Password123NewPassword123 xml 应该在 2 个地方更改:

<Params Key="Password" Value="Password123">

<Value>Password123</Value>

如何才能做到这一点?

编辑XML 已经存在,而不是我的设计。我只需要改变它

我尝试使用 XDocument,但查询时遇到问题。你能提供一个知道如何查询它的 linq 吗?

4

3 回答 3

1

使用 LINQ to XML 怎么样?

var doc = XDocument.Parse(xmlString);

var passwordParams = doc.Root.Elements("Params").SingleOrDefault(e => (string)e.Attribute("Key") == "Password");

if(passwordParams != null)
{
    passwordParams.Attribute("Value").Value = newPasswordString;
    passwordParams.Element("Variable").Element("Value").Value = ewPasswordString;
}

之后,您可以将文档保存在您想要的任何位置。

我现在无法测试它,但总体思路应该很清楚。

于 2012-12-23T09:45:35.340 回答
0

这将是一种方法 - 使用“旧”样式XmlDocument类将整个 XML 加载到内存中并允许您“导航”其结构。如果您的 XML 不是太大(如这里),则可以正常工作。

// create XML document and load contents from file
XmlDocument xdoc = new XmlDocument();
xdoc.Load(@"D:\temp\test.xml");   // adapt this to your own path!

// get the <Params> node with the Key=Password attribute
XmlNode paramsNode = xdoc.SelectSingleNode("/ArrayOfParams/Params[@Key='Password']");

if (paramsNode != null)
{
    // set the value of the "Value" attribute to the new password
    paramsNode.Attributes["Value"].Value = "NewPassword123";

    // get the "Variable/Value" subnode under that <Params> node
    XmlNode valueSubnode = paramsNode.SelectSingleNode("Variable/Value");

    if (valueSubnode != null)
    {
       valueSubnode.InnerText = "NewPassword123";

       // save XmlDocument back out to a new file name
       xdoc.Save(@"D:\temp\modified.xml");
    }
}
于 2012-12-23T09:45:55.917 回答
0

使用 System.Xml.XmlDocument 非常简单:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(source);
XmlNode password = xmlDocument.SelectSingleNode("//Params[@Key='Password']");
password.Attributes["Value"] = "NewPassword123";
XmlNode value = password.SelectSingleNode("./Value");
value.InnerXml = "NewPassword123";
string source = xmlDocument.OuterXml;
xmlDocument.Save(destPath);

希望这对您有所帮助。

于 2012-12-23T09:46:05.610 回答