【问题标题】:Removing element value of the following element删除以下元素的元素值
【发布时间】:2014-09-28 17:45:02
【问题描述】:

我想从以下 XDocument 结构中删除特定值:

<plist version="1.0">
<dict>
<key>Main</key>
<array>
    <dict>
        <key>Password</key>
        <string>*********</string>
        <key>Username</key>
        <string>testuser</string>
    </dict>
</array>
<key>Profile</key>
<string>test profile 1</string>
</dict>
</plist>

假设我想删除与 key=Password 关联的字符串值,我该怎么做?

【问题讨论】:

标签: c# linq-to-xml


【解决方案1】:

您可以使用 XPath 检索密码元素并重置其内容:

var passwords = document.XPathSelectElements("//key[text()='Password']/following-sibling::string[1]");
foreach(XNode elem in passwords)
{
  elem.SetValue(string.Empty);
}

当然,接下来你必须将文档保存回来。

它的作用是识别密码关键元素,然后识别下一个兄弟元素。这假定顺序始终与您的示例中的相同:第一个键,然后是字符串。

你可以check it here, online

当然还有this solution with Linq to XML

【讨论】:

  • 我在您的代码中没有看到任何引用 &lt;string&gt; 元素的内容。密码不是 &lt;password&gt; 元素中嵌入的 XNode。
  • @RobertHarvey:已更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 2015-08-03
  • 1970-01-01
相关资源
最近更新 更多