我有一个XML文件,其中包含一些节点及其子节点,有时具有相同的名称和属性。
<?xml version="1.0"?>
<PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
<Address Type="Shipping">
<Name>Ellen Adams</Name>
<Street>123 Maple Street</Street>
<City>Mill Valley</City>
<State>CA</State>
<Zip>10999</Zip>
<Country>USA</Country>
</Address>
<Address Type="Billing">
<Name>Tai Yee</Name>
<Street>8 Oak Avenue</Street>
<City>Old Town</City>
<State>PA</State>
<Zip>95819</Zip>
<Country>USA</Country>
<Address Type="Buying">
<Name>Ellen Adams</Name>
</Address>
<Address Type="transporting">
<Name>Tai Yee</Name>
<Street>8 Oak Avenue</Street>
</Address>
</Address>
<DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>
<Items>
<Item PartNumber="872-AA">
<ProductName>Lawnmower</ProductName>
<Quantity>1</Quantity>
<USPrice>148.95</USPrice>
<Comment>Confirm this is electric</Comment>
</Item>
<Item PartNumber="926-AA">
<ProductName>Baby Monitor</ProductName>
<Quantity>2</Quantity>
<USPrice>39.98</USPrice>
<ShipDate>1999-05-21</ShipDate>
</Item>
</Items>
</PurchaseOrder>
我希望只有Address
个节点及其属性作为输出。问题是有一些嵌套节点将Address
节点作为子节点。访问孩子Address
是我的问题。如果它再次具有名为Address
的子节点,那么我不想像我在以下代码中那样给我这个节点
public void find_node(string ID_node)
{
XElement root = XElement.Load("PurchaseOrder.xml");
IEnumerable<XElement> address =
from el in root.Elements("Address")
where (string)el.Attribute("Type") == "Buying"
select el;
foreach (XElement el in address)
{
var newElement = new XElement(
el.Name.LocalName,
el.Attributes(),
el.Elements().Where(o => o.Name.LocalName != "Address")
);
Console.WriteLine(newElement.ToString());
}
}
此代码的所需输出为
<Address Type="Buying">
<Name>Ellen Adams</Name>
</Address>
但是当我运行上述函数时它的输出为空。
我可以问你能为这个功能获得空输出吗?
答案 0 :(得分:1)
如果您要查找Address
元素,无论其在XML中的位置如何,只要它与属性过滤器匹配,您就可以使用Descendants("Address")
代替:
IEnumerable<XElement> address =
from el in root.Descendants("Address")
where (string)el.Attribute("Type") == "Buying"
select el;
答案 1 :(得分:0)
IEnumerable<XElement> address =
from el1 in root.Elements("Address")
from el2 in el1.Elements("Address")
where (string)el2.Attribute("Type") == "Buying"
select el2;