Skip to main content
 首页 » 编程设计

c#之如何重写此 Linq to XML 查询

2024年02月23日20leader

与 XMLReader 相比,我更喜欢 LINQ to XML,因为它感觉更容易使用。但是,我知道我在某处做错了。我不是在寻找更快的执行速度或任何东西,只是更干净的重写。我不知道它是否完全适合 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 - 字符串、整数、整数

如果它有点清晰,文件的总体布局:

  • 具有名称属性的根节点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); 

但老实说,我认为您的原始代码很好。