2014-02-20 66 views
0

我有一个XML如下面的XML,遍历在c#

<product> 
    <ProductId>3</ProductId> 
    <ProductName>Voice Recognition</ProductName> 
</product> 
<product> 
    <ProductId>5</ProductId> 
    <ProductName>TravelExpert Settings</ProductName> 
    <ProductAttribute> 
    <Name>AllowbookIncompleteTraveller</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>CreateTravs</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>MultiPax</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>Hotel</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>Profile</Name> 
    <Description>true</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>Air</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>TicketDelivery</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>Exchange</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>Car</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>Itinerary</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
    <ProductAttribute> 
    <Name>StoredFare</Name> 
    <Description>false</Description> 
    </ProductAttribute> 
</product> 

我需要遍历与产品名称=“TravelExpert设置”产品,其下我需要ProductAttribute的值与名称=“资料”。值是真的。元素的类型是System.Xml.Linq.XElement。

我可以请这个帮忙吗?如果您需要进一步说明,请告诉我。

非常感谢。

谢谢!

+0

夫妇的选择。您可以使用[.NET序列化支持](http://msdn.microsoft.com/en-us/library/58a18dwa(v = vs.110).aspx),并简单地对对象建模,反序列化,然后使用LINQ查找你需要的价值。第二种选择是使用[XPath](http://msdn.microsoft.com/en-us/library/ms256086(v = vs.110).aspx)查找所需的节点。 – LB2

+0

是的,我与之合作的团队对这些概念并不是很了解。这是我的第一个建议。 – OBL

回答

3
  1. 您的XML无效。 XML文档不能包含多个根元素。我假定你的文档看起来像:

    <products> 
        <product> 
        <ProductId>3</ProductId> 
        <ProductName>Voice Recognition</ProductName> 
        </product> 
        <product> 
        <ProductId>5</ProductId> 
        <ProductName>TravelExpert Settings</ProductName> 
        <ProductAttribute> 
         <Name>AllowbookIncompleteTraveller</Name> 
         <Description>false</Description> 
        </ProductAttribute> 
        <!-- (...) --> 
        </product> 
    </products> 
    
  2. 您的查询应该是这样的:

    var xDoc = XDocument.Load("Input.xml"); 
    
    var valueElement = xDoc.Root 
             .Elements("product") 
             .First(p => (string)p.Element("ProductName") == "TravelExpert Settings") 
             .Elements("ProductAttribute") 
             .First(pa => (string)pa.Element("Name") == "Profile") 
             .Element("Description"); 
    
    var value = (bool)valueElement; 
    
+0

感谢您抽出宝贵时间帮忙,我试了一下,发现错误“Expression不能包含lambda表达式” – OBL

+0

它不在即时窗口中工作,但逻辑完美无瑕。谢谢。 – OBL