c# - 如何只处理某些 XML 节点?

标签 c# xpath

这是我的 XML 片段(它有一个根元素)。

<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();

关于c# - 如何只处理某些 XML 节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9455267/

相关文章:

c# - 如何让 QnA Maker 和 Luis BOT 的集成准确工作?

c# - System.Int32 和 int 的 MSIL 会相同吗?

c# - 在另一个项目中读取 JSON 文件时出现问题

Php Xpath - 如何获取子节点中的两个信息

javascript - 从 Javascript 调用 aspx 代码隐藏中的函数会引发错误

c# - 为什么 Container.DataItem 作为字符串文字传递?

xpath 1 和 xpath 2 在确定最小值和最大值时返回不同的结果

xml - 如何使用 xidel 连接两个提取的值?

xpath - 使用Xpath获取YouTube视频的时长

python - normalize-space 只适用于 xpath 而不是 css 选择器