获取xml中的所有子项详细信息?

时间:2014-08-19 17:54:17

标签: xml linq c#-3.0

我有一个xml,我想从中获取数据。我将传递一个键Comp1 /,我应该获取值并将其存储在字典中。例如,在XML中,当我传递地址时,我应该返回Housno,Street,City和Country作为名称值对。如果我通过电子邮件,我应该返回电子邮件作为名称值对。我正在尝试使用LINQ to XML。我曾经使用

获取电子邮件的价值
resuls = (var res in xDoc.Descendant("Comp1/Email")
    select new
  {
      Name1 = res.Name,
      Values = res.Value,   
   }).ToDictionary<string,string>(a=>res.Name1,a=>Values);

如果我通过地址我没有得到确切的结果。我做错了什么?我还包括一个样本xml

      <Companies>
    <Comp1>
      <Name>Comp1</Name>
      <Address>
        <HouseNo>3</HouseNo>
        <Street>Street</Street>
        <City>Delhi</City>
        <Country>India</Country>
      </Address>
      <Email>test@test.com</Email>
    </Comp1>
    <Comp2>
      <Name>Comp2</Name>
      <Address>
        <HouseNo>1</HouseNo>
        <Street>Street1</Street>
        <City>Delhi</City>
        <Country>India</Country>
      </Address>
      <Email>test@test1.com</Email>
    </Comp2>
  </Companies>

谢谢, Jollyguy

[编辑]

我已经运行了你的代码并且它可以工作,但我想要一个通用的解决方案,如果我将来在节点内添加多个节点(只有第一级子节点),它将会起作用。我能够使用XMLDocument这样做,我试图使用LINQ做同样的事情。请在下面找到我的代码

Dictionary<string, string> dictValus = new Dictionary<string, string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("d:\\test.xml");
string companyname = "Comp1";
string findname = "Email";
XmlNodeList xmlList = xmlDoc.SelectNodes("Companies/" + companyname +"/" + findname);

foreach (XmlNode node in xmlList)
{
    if (node.FirstChild.Name.ToString() != node.LastChild.Name.ToString())
    {
        foreach (XmlNode childNode in node.ChildNodes)
        {
            dictValus.Add(childNode.LocalName, childNode.InnerText);
        }
    }
    else
    {
        dictValus.Add(node.LocalName, node.InnerText);
    }
}

[/编辑]

1 个答案:

答案 0 :(得分:0)

希望这可以提供帮助:

void Main()
{
    var xml=XDocument.Load("d:\\test.xml");
    string key="Email";
    var list=xml.Descendants("Companies").Elements() 
                .Select(x=>new
                        {
                            Name=x.Element("Name"),
                            Email=x.Element("Email"),
                            Address=x.Element("Address")
                        });
    var result=new Dictionary<string,string>();
    switch(key)
    {
       case "Email":
             result=list.Select(x=>new{Key=x.Name.Value+"/"+x.Email.Name,Value=x.Email.Value})
                           .ToDictionary(x=>x.Key,x=>x.Value);

        break;
        case "Address":
             result=list.Select(x=>new{Key=x.Name.Value+"/"+x.Address.Name,Value=string.Join(",",x.Address.Elements().Select(a=>a.Value).ToArray())})
                           .ToDictionary(x=>x.Key,x=>x.Value);


         break; 
    }

    result.Dump();
}