首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ReplaceWith linq字典

ReplaceWith linq字典
EN

Stack Overflow用户
提问于 2020-05-13 20:36:52
回答 1查看 52关注 0票数 0

有人能帮我做这件事吗。我们有xml文件test.xml

代码语言:javascript
复制
<?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>

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

代码语言:javascript
复制
<root>
  Lorem ipsum <key name="k1"/>
  <local> guest=Alice </local>
  Hello Alice.
  Goodbye Bob.
  End
  <key name="k3"/>
</root>

将Dictionary和Linq用于xml。我的代码

代码语言:javascript
复制
    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));;
    }

和我的输出

代码语言:javascript
复制
  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。抱歉,我的英语不好

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-18 12:55:06

你差点就到了。如果您在template元素上的迭代和key元素上的迭代之间进行分离,我认为您会立即注意到解决方案。

所以这里是:

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61784368

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档