解析复杂嵌套的XML

时间:2017-08-02 08:00:59

标签: c# xml linq-to-xml

我一直在阅读各种教程,但无法有条理地解析以下XML结构,其中用户输入State的名称,然后接收Capitol的名称。

当我使用以下代码测试它时,我没有弹出MessageBox。

C#代码

XDocument xd = XDocument.Load("Foo.xml");

foreach (var state in xd.Descendants("State"))
{
      Messagebox.Show(state.Attribute("Name").Value);
}

Foo.xml

<Main>
   <Title></Title>
   <Planet Name="Earth">
      <Continent Name="North America">
         <Country Name="USA">
            <State Name="Illinois" Capital="Springfield"></State>
            <State Name="Alabama" Capital="Montgomery"></State>
            ...
         </Country>
         <Country Name="Canada">
            <State Name="Alberta" Capital="Edmonton"></State>
            <State Name="British Columbia" Capital="Victoria"></State>  
            <State Name="Manitoba" Capital="Winnipeg"></State>
            ....
         </Country>
         <Country> ... </Country>
         <Country> ... </Country>
         <Country> ... </Country>
      </Continent>
   </Planet>
</Main>

2 个答案:

答案 0 :(得分:1)

这应该有效:

List<State> states = (from s in XDocument.Load(@"Foo.xml").Descendants("State")
    select new State
    {
        Name = s.Attribute("Name").Value,
        Capital = s.Attribute("Capital").Value
    }).ToList();

foreach (State state in states)
{
    //do something...
}

//Or get a specific state
var alabama = states.FirstOrDefault(a => a.Name == "Alabama");

答案 1 :(得分:1)

我稍微修改了你的代码。这将使你从国家返回国会大厦。

var stateCapital = from states in XDocument.Load(@"foo.xml").Descendants("State")
                    where states.Attribute("Name").Value == "Alabama"
                    select states.Attribute("Capital").Value;

Messagebox.Show(stateCapital);

如果你需要for循环中每个状态的所有Capitals的名字 -

var statesCollection = from states in XDocument.Load(@"foo.xml").Descendants("State") select states;

foreach (var state in statesCollection)
{
    Messagebox.Show(state.Attribute("Capital").Value);
}