【问题标题】:Use C# to loop through XML document and if condition is met replace value or node使用 C# 循环遍历 XML 文档,如果满足条件,则替换值或节点
【发布时间】:2020-08-27 16:23:22
【问题描述】:

我有一个带有 XML XDocument xdoc1 = XDocument.Load(doc1)XDocument 我想遍历 XML 文档,如果满足条件,则替换值或节点。

我试过这样的代码:

var list = from item in xdoc1.Root.Element("New").Elements() select item;
        
foreach (XElement item in list)
{
    foreach (var node in item.Nodes())
    {
        if (node.ToString() == "DIV||<Control>")
        {
            item.Element("Value").Value = "DIV||TextBox";
        }
    }

但这对我不起作用。

如果我的 XML 看起来像这样

<Test>
  <New>
    <DoSometing>
      <Selector>
      </Selector>
      <Value>DIV||&lt;Control&gt;</Value>
    </DoSometing>
    <DoSometingElse>
      <Selector>
      </Selector>
      <Value>DIV||&lt;Control&gt;</Value>
    </DoSometingElse>
  </New>
</Test>

所以我的想法是遍历所有的xml,如果条件==&amp;lt;Control&amp;gt;然后替换它。

我也试过像IEnumerable&lt;XElement&gt; list = from item in xdoc1.Root.Element("New").Elements() where (item.Name == "Value") select item;这样的suff

【问题讨论】:

  • 您能否提供更多关于什么不工作的信息,即错误或堆栈跟踪?此外,了解正在处理的 XML 是否与发布的 XML 不同也会很有帮助;示例中没有名称为 TestSteps 的元素。

标签: c# xml linq


【解决方案1】:

您可以考虑过滤查询块中的元素,并仅对必要的元素应用更新。注意这里使用的是XElement.Value,所以必须使用解码后的元素值。

var list = from item in xdoc1.Root.Element("New").Elements().Elements("Value") 
           where item.Value == "DIV||<Control>"
           select item;

foreach (XElement item in list)
{
    item.Value = "DIV||TextBox";
}

【讨论】:

    【解决方案2】:

    比较简单的版本。

    c#

    void Main()
    {
        const string fileName = @"e:\temp\hala.xml";
        const string searchFor = "DIV||<Control>";
        const string replaceWith = "789";
    
        //XDocument xdoc = XDocument.Load(fileName);
        XDocument xdoc = XDocument.Parse(@" < Test >
        <New>
            <DoSometing>
                <Selector>
                </Selector>
                <Value>DIV||&lt;Control&gt;</Value>
            </DoSometing>
            <DoSometingElse>
                <Selector>
                </Selector>
                <Value>DIV||&lt;Control&gt;</Value>
            </DoSometingElse>
        </New>
    </Test>");
    
        // step #1: find element(s) based on the search value
        var xmlFragment = xdoc.Descendants("Value")
           .Where(d => d.Value.Equals(searchFor));
        
        // step #2: if found, set its value
        foreach (XElement element in xmlFragment)
        {
            element.SetValue(replaceWith);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多