如何逐个获取xml中子节点的值

时间:2018-02-22 06:39:49

标签: c# xml

如何从此xml文件中读取asin及其值。 我在这个xml文件中有多个产品。 这两个产品就像我想要的那样。

 XDocument xdoc = XDocument.Load(@"D:\Product\WriteText2.xml");
        XElement match = xdoc.Root.Element("GetMatchingProductForIdResult");

        foreach(XElement product in match.Elements("Products"))
        {
            XElement asin = product.Element("Identifiers").Element("MarketplaceASIN").Element("ASIN");
            string asinValue = asin.Value;
        }    

      <GetMatchingProductForIdResult Id="619659000431" IdType="UPC" status="Success">
            <Products>
              <Product>
                <Identifiers>
                  <MarketplaceASIN>
                    <MarketplaceId>A21TJRUUN4KGV</MarketplaceId>
                    <ASIN>B002U1ZBG0</ASIN>
                  </MarketplaceASIN>
                </Identifiers> 
                </Product>
        </Products>
      </GetMatchingProductForIdResult>
 <GetMatchingProductForIdResult Id="190198462411" IdType="UPC" status="Success">
    <Products>
      <Product>
        <Identifiers>
          <MarketplaceASIN>
            <MarketplaceId>A21TJRUUN4KGV</MarketplaceId>
            <ASIN>B073Q5R6VR</ASIN>
          </MarketplaceASIN>
        </Identifiers>
</Product>
    </Products>
  </GetMatchingProductForIdResult>

1 个答案:

答案 0 :(得分:1)

您可以使用System.Xml.Linq

XDocument xdoc = XDocument.Load("file.xml");
XElement match = xdoc.Element("GetMatchingProductForIdResult");

foreach(XElement product in match.Elements("Products")){
    XElement asin = product.Element("Identifiers")
        .Element("MarketplaceASIN").XElement("ASIN");
    string asinValue = asin.Value;
}