有人能帮我做这件事吗。我们有xml文件test.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>在文件中,我们有节点“模板”,我们必须搜索带有属性名称的节点"key“,并用字典密钥对值替换它。并将其保存在test.out.xml中
<root>
Lorem ipsum <key name="k1"/>
<local> guest=Alice </local>
Hello Alice.
Goodbye Bob.
End
<key name="k3"/>
</root>将Dictionary和Linq用于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。抱歉,我的英语不好
发布于 2020-05-18 12:55:06
你差点就到了。如果您在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);
}https://stackoverflow.com/questions/61784368
复制相似问题