如何只处理某些XML节点?

提问

这是我的XML代码段(它具有一个root元素).

<ItemAttributes>
    <Author>Ellen Galinsky</Author>
    <Binding>Paperback</Binding>
    <Brand>Harper Paperbacks</Brand>
    <EAN>9780061732324</EAN>
    <EANList>
        <EANListElement>9780061732324</EANListElement>
    </EANList>
    <Edition>1</Edition>
    <Feature>ISBN13: 9780061732324</Feature>
    <Feature>Condition: New</Feature>
    <Feature>Notes: BRAND NEW FROM PUBLISHER! 100% Satisfaction Guarantee. Tracking provided on most orders. Buy with Confidence! Millions of books sold!</Feature>
    <ISBN>006173232X</ISBN>
    <IsEligibleForTradeIn>1</IsEligibleForTradeIn>
    <ItemDimensions>
        <Height Units="hundredths-inches">112</Height>
        <Length Units="hundredths-inches">904</Length>
        <Weight Units="hundredths-pounds">98</Weight>
        <Width Units="hundredths-inches">602</Width>
    </ItemDimensions>
    <Label>William Morrow Paperbacks</Label>
    <ListPrice>
        <Amount>1699</Amount>
        <CurrencyCode>USD</CurrencyCode>
        <FormattedPrice>$16.99</FormattedPrice>
    </ListPrice>
    <Manufacturer>William Morrow Paperbacks</Manufacturer>
    <MPN>006173232X</MPN>
    <NumberOfItems>1</NumberOfItems>
    <NumberOfPages>400</NumberOfPages>
    <PackageDimensions>
        <Height Units="hundredths-inches">120</Height>
        <Length Units="hundredths-inches">880</Length>
        <Weight Units="hundredths-pounds">95</Weight>
        <Width Units="hundredths-inches">590</Width>
    </PackageDimensions>
    <PartNumber>006173232X</PartNumber>
    <ProductGroup>Book</ProductGroup>
    <ProductTypeName>ABIS_BOOK</ProductTypeName>
    <PublicationDate>2010-04-20</PublicationDate>
    <Publisher>William Morrow Paperbacks</Publisher>
    <ReleaseDate>2010-04-20</ReleaseDate>
    <SKU>mon0000013657</SKU>
    <Studio>William Morrow Paperbacks</Studio>
    <Title>Mind in the Making: The Seven Essential Life Skills Every Child Needs</Title>
</ItemAttributes>

有多个“ ItemAttributes”节点,每个节点都有一个不同的“ ProductGroup”节点.我只想要第一个“ ItemAttribute”,其中“ ProductGroup” =“ book:”

这是我的C#代码:

    XPathDocument doc = new XPathDocument(sr);
    XPathNavigator nav = doc.CreateNavigator();

    // Compile a standard XPath expression
    XPathExpression expr;
    expr = nav.Compile("//ItemAttributes[contains(ProductGroup, 'Book')]");
    XPathNodeIterator iterator = nav.Select(expr);

    // Iterate on the node set
    try {
        int x = iterator.Count;  //  <----------- count = 0
        while (iterator.MoveNext()) {  //  <-----------  finds nothing!
            XPathNavigator nav2 = iterator.Current.Clone();
            listBox1.Items.Add("price: " + nav2.Value);
        }
    }
    catch (Exception ex) {
        Console.WriteLine(ex.Message);
    }

我知道我的代码不正确,但是我不明白为什么iterator.Count为零!

最佳答案

使用System.Xml.Linq

XDocument xdoc = XDocument.Load(new StringReader(xmlstr)); 
var foundNode = xdoc
    .Descendants("ItemAttributes")
    .Where(node => node.Element("ProductGroup").Value == "Book")
    .First();

var price = foundNode.Element("ListPrice").Element("FormattedPrice").Value;

– 编辑 –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlstr = @"
                    <root>
                    <ItemAttributes>
                    <Author>Ellen Galinsky</Author>
                    <Binding>Paperback</Binding>
                    <Brand>Harper Paperbacks</Brand>
                    <EAN>9780061732324</EAN>
                    <EANList>
                    <EANListElement>9780061732324</EANListElement>
                    </EANList><Edition>1</Edition>
                    <Feature>ISBN13: 9780061732324</Feature>
                    <Feature>Condition: New</Feature>
                    <Feature>Notes: BRAND NEW FROM PUBLISHER! 100% Satisfaction Guarantee. Tracking provided on most orders. Buy with Confidence! Millions of books sold!</Feature>
                    <ISBN>006173232X</ISBN>
                    <IsEligibleForTradeIn>1</IsEligibleForTradeIn>
                    <ItemDimensions>
                    <Height Units=""hundredths-inches"">112</Height>
                    <Length Units=""hundredths-inches"">904</Length>
                    <Weight Units=""hundredths-pounds"">98</Weight>
                    <Width Units=""hundredths-inches"">602</Width>
                    </ItemDimensions>
                    <Label>William Morrow Paperbacks</Label>
                    <ListPrice>
                    <Amount>1699</Amount>
                    <CurrencyCode>USD</CurrencyCode>
                    <FormattedPrice>$16.99</FormattedPrice>
                    </ListPrice>
                    <Manufacturer>William Morrow Paperbacks</Manufacturer>
                    <MPN>006173232X</MPN>
                    <NumberOfItems>1</NumberOfItems>
                    <NumberOfPages>400</NumberOfPages>
                    <PackageDimensions>
                    <Height Units=""hundredths-inches"">120</Height>
                    <Length Units=""hundredths-inches"">880</Length>
                    <Weight Units=""hundredths-pounds"">95</Weight>
                    <Width Units=""hundredths-inches"">590</Width>
                    </PackageDimensions>
                    <PartNumber>006173232X</PartNumber>
                    <ProductGroup>Book</ProductGroup>
                    <ProductTypeName>ABIS_BOOK</ProductTypeName>
                    <PublicationDate>2010-04-20</PublicationDate>
                    <Publisher>William Morrow Paperbacks</Publisher>
                    <ReleaseDate>2010-04-20</ReleaseDate>
                    <SKU>mon0000013657</SKU>
                    <Studio>William Morrow Paperbacks</Studio>
                    <Title>Mind in the Making: The Seven Essential Life Skills Every Child Needs</Title>
                    </ItemAttributes>
                    </root>
                    ";
            XDocument xdoc = XDocument.Load(new StringReader(xmlstr));
            var foundNode = xdoc
                .Descendants("ItemAttributes")
                .Where(node => node.Element("ProductGroup").Value == "Book")
                .First();

            Console.WriteLine(foundNode.Element("ListPrice").Element("FormattedPrice").Value);
            Console.ReadLine();

        }
    }
}

-编辑2–

XDocument xdoc = XDocument.Load("http://ecs.amazonaws.com/onca/xml?AWSAccessKeyId=AKIAIAAFYAPOR6SX5GOA&AssociateTag=pragbook-20&IdType=ISBN&ItemId=9780061732324&MerchantId=All&Operation=ItemLookup&ResponseGroup=Medium&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2012-02-26T20%3A18%3A37Z&Version=2011-08-01&Signature=r7yE7BQI44CqWZAiK%2FWumF3N4iutOj3re9wZtESOaKs%3D");
XNamespace ns = XNamespace.Get("http://webservices.amazon.com/AWSECommerceService/2011-08-01");
var foundNode = xdoc
    .Descendants(ns+"ItemAttributes")
    .Where(node => node.Element(ns+"ProductGroup").Value == "Book")
    .First();

Console.WriteLine(foundNode.Element(ns+"ListPrice").Element(ns+"FormattedPrice").Value);
Console.ReadLine();