我发现在 XML 中使用属性和嵌套元素很困难。
如果我只想提取Phone
具有属性的元素Type="Mobile"
并在一行中打印地址?
我想产生这样的输出:
332-899-5678 | 123 Main, St Mercer Island, WA 68042
请帮忙,下面是我的示例 xml 文件
<Contacts>
<Contact>
<Name>Patrick Hines</Name>
<Phone Type="Home">206-555-0144</Phone>
<Phone Type="Work">425-555-0145</Phone>
<Phone Type="Mobile">332-899-5678</Phone>
<Address>
<Street1>123 Main St</Street1>
<City>Mercer Island</City>
<State>WA</State>
<Postal>68042</Postal>
</Address>
</Contact>
</Contacts>
string xml = @"<Contacts>
<Contact>
<Name>Patrick Hines</Name>
<Phone Type=""Home"">206-555-0144</Phone>
<Phone Type=""Work"">425-555-0145</Phone>
<Phone Type=""Mobile"">332-899-5678</Phone>
<Address>
<Street1>123 Main St</Street1>
<City>Mercer Island</City>
<State>WA</State>
<Postal>68042</Postal>
</Address>
</Contact>
<Contact>
<Name>Dorothy Lee</Name>
<Phone Type=""Home"">910-555-1212</Phone>
<Phone Type=""Work"">336-555-0123</Phone>
<Phone Type=""Mobile"">336-555-0005</Phone>
<Address>
<Street1>16 Friar Duck Ln</Street1>
<City>Greensboro</City>
<State>NC</State>
<Postal>27410</Postal>
</Address>
</Contact>
</Contacts>";
XDocument document = XDocument.Parse(xml);
var query = from contact in document.Descendants("Contact")
let address = contact.Element("Address")
select new
{
Name = contact.Element("Name").Value,
MobilePhone = contact.Elements("Phone").Where(ele => ele.Attribute("Type").Value == "Mobile").First().Value,
Street1 = address.Element("Street1").Value,
City = address.Element("City").Value,
State = address.Element("State").Value,
Postal = address.Element("Postal").Value
};
foreach (var item in query)
{
Console.WriteLine("{0} | {1}, {2}, {3} {4}", item.MobilePhone, item.Street1, item.City, item.State, item.Postal);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)