【问题标题】:ReplaceWith linq xml dictionaryReplaceWith linq xml 字典
【发布时间】:2020-05-13 20:36:52
【问题描述】:

有人可以帮我完成这项工作吗? 我们有文件 xml 文件 测试.xml

<?xml version="1.0" encoding="utf-8" ?>
<root>
  Lorem ipsum <key name="k1"/>
  <local> <template> guest=<key name="k1"/> </template> </local>
  <template>
    Hello <key name="k1"/>.
    Goodbye <key name="k2"/>.
    End
    <key name="k3"/>
  </template>
</root>

在文件中,我们有节点“模板”,我们必须用属性名称搜索节点“键”并用字典键对值替换它。并将其保存在 test.out.xml 中

<root>
  Lorem ipsum <key name="k1"/>
  <local> guest=Alice </local>
  Hello Alice.
  Goodbye Bob.
  End
  <key name="k3"/>
</root>

使用 Dictionary 和 Linq to xml。 我的代码

    foreach (var elements in xdoc.Descendants("template").ToList().Elements("key"))
    {
        elements.Attribute("name").Parent.ReplaceWith(dict.Where(x
            => elements.Attribute("name").Value == x.Key).Select(p => p.Value));;
    }

和我的输出

  Lorem ipsum <key name="k1" /><local><template> guest=Alice</template></local><template>
    Hello Alice.
    Goodbye <key name="k2" />.
    End
    <key name="k3" /></template></root>

问题是,我通过名称属性中的值在字典中按键更改, 但我不能删除文件中的模板:( p.s. 对不起我的英语不好

【问题讨论】:

  • 我的回答是否帮助您解决了问题?如果是这样,请通过勾选左侧的 V 将其标记为已接受。如果没有,请告诉我,我会尽力为您提供进一步的帮助

标签: c# xml linq


【解决方案1】:

你快到了。如果您将template 元素的迭代和key 元素的迭代分开,我想您会立即注意到解决方案。

原来是这样:

var replacers = new Dictionary<string, string> { { "k1", "Alice" }, { "k2", "Bob" }, { "k3", "Carol" } };
var templates = xdoc.Root.Descendants("template").ToList();
foreach (var template in templates)
{
    var toReplace = template.Descendants("key").ToList();
    foreach (var element in toReplace)
    {
        element.ReplaceWith(replacers[element.Attribute("name").Value]);  
    }
    template.ReplaceWith(template.Value);
}

【讨论】:

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