[英]How can I rewrite this Linq to XML query?
我更喜欢 LINQ 到 XML 而不是 XMLReader,因为它感觉更容易使用。 但是,我知道我在某处做错了。 我不是在寻找更快的执行或任何东西,只是更干净的重写。 我不知道它是否完全适合from foo in bar where foo is some condition
形式,但必须有一种更清洁的方式。
我在这里没有使用匿名对象,而是作为字符串输出,因为我排除了一些将数据适应现有对象的代码 - 但是,它是一种目前我需要重构的凌乱结构。
我的 XML 看起来像这样。
<?xml version="1.0" encoding="utf-8" ?>
<entity name="Something">
<Component type="RenderComponent">
<Material type="string">fur</Material>
<Reflectiveness type="int">678</Reflectiveness>
</Component>
<Component type="HealthComponent">
<Sound type="int">60</Sound>
</Component>
</entity>
我的代码:
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load(@"..\..\XMLFile1.xml");
List<string> comNames = new List<string>();
Dictionary<string, string> paramValues = new Dictionary<string, string>();
List<string> paramTypes = new List<string>();
foreach (XElement e in xdoc.Root.Elements("Component"))
{
string type = e.Attribute("type").Value;
foreach(XElement param in e.Elements())
{
paramValues.Add(param.Name.LocalName, param.Value);
paramTypes.Add(param.Attributes().First().Value);
}
Console.WriteLine(" \n\n\n");
comNames.Add(type);
}
}
提供以下输出:
comNames - RenderComponent, HealthComponent
paramValues - (Material, fur), (Reflectiveness, 678), (Sound, 60)
paramTypes - string, int, int
如果它有点清除它,文件的一般布局:
name
属性的根节点entity
(在此示例中忘记了)n
具有type
属性的组件节点Component
节点都有许多子节点,这些子节点具有名称、 type
属性和value
。我认为,您可以执行以下操作:
XDocument xdoc = XDocument.Load(@"..\..\XMLFile1.xml");
var data =
xdoc.Root.Elements("Component")
.SelectMany(e => new
{
type = e.Attribute("type").Value,
paramValues = e.Elements()
.Select(x => new KeyValuePair<string,
string>
(x.Name.LocalName,
x.Value)),
paramType = e.Elements()
.Select(x => x.Attributes().First()
.Value)
});
List<string> comNames = data.Select(x => x.type).ToList();
List<string> paramTypes = data.Select(x => x.paramType).ToList();
Dictionary<string, string> paramValues = data.Select(x => x.paramValues)
.ToDictionary(x => x.Key,
x => x.Value);
但老实说,我认为您的原始代码很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.