<?xml version="1.0" encoding="UTF-8"?>
<root>
<level1 name="abc1" type="xyz">
<data name="A" count="23" avg="56" />
<data name="B" count="67" avg="18" />
<data name="C" count="42" avg="23" />
</level1>
<level1 name="abc2" type="xyz">
<data name="B" count="56" avg="29" />
<data name="C" count="23" avg="64" />
<data name="E" count="78" avg="21" />
</level1>
</root>
如果过滤器列表是{A,C,E,F},并且想要使用列表中具有其name属性值的所有数据过滤上述文档。如果找不到匹配的元素,我仍然希望将具有该名称的数据元素和该元素的所有其他属性设置为某些默认值:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<level1 name="abc1" type="xyz">
<data name="A" count="23" avg="56" />
<data name="C" count="42" avg="23" />
<data name="E" count="0" avg="0" />
<data name="F" count="0" avg="0" />
</level1>
<level1 name="abc2" type="xyz">
<data name="A" count="0" avg="0" />
<data name="C" count="23" avg="64" />
<data name="E" count="78" avg="21" />
<data name="F" count="0" avg="0" />
</level1>
</root>
此外,我还可以根据选择标准仅选择我想要的属性。
答案 0 :(得分:0)
以下是一些产生您发布的输出的C#示例代码:
XDocument input = XDocument.Load("input.xml");
XDocument output = new XDocument(
new XElement(input.Root.Name,
from level in input.Root.Elements("level1")
select new XElement("level1",
level.Attributes(),
from name in new string[] { "A", "C", "E", "F" }
let data = level.Elements("data").FirstOrDefault(d => d.Attribute("name").Value == name)
select (data != null ? data : new XElement("data",
new XAttribute("name", name),
new XAttribute("count", 0),
new XAttribute("avg", 0)
)))));
output.Save("output.xml");