提取XML的特定部分

时间:2012-12-24 07:54:42

标签: c# .net xml xml-parsing

我在字符串变量中有一个XML,我想检查这个xml内容是否包含

<xml>
<message display='yes'>
....

<xml>
<xdp:xdp>
...

有可能吗?

2 个答案:

答案 0 :(得分:1)

以下是检查方法:

        string example = @"<xml>
            <message display='yes'></message>
            </xml>";

        XDocument doc = XDocument.Parse(example);
        if (doc.Element("xml").Element("message") != null)
        {
            // node "message" exists within node "xml" which is located at the root of the document
        }

您可以使用XDocument类检查XML文档层次结构中任何位置是否存在任何节点。您可以轻松地从字符串或文件加载内容。

答案 1 :(得分:0)

以下示例

<Order>
  <AmazonOrderID>000-1111111-2222222</AmazonOrderID>
  <MerchantOrderID>111-3333333-4444444</MerchantOrderID>
  <PurchaseDate>2012-03-02T13:28:53+00:00</PurchaseDate>
  <LastUpdatedDate>2012-03-02T13:29:05+00:00</LastUpdatedDate>
  <OrderStatus>Pending</OrderStatus>
  <SalesChannel>Amazon.com</SalesChannel>
  <URL>http://www.amazon.com</URL>
  <FulfillmentData>
    <FulfillmentChannel>Amazon</FulfillmentChannel>
    <ShipServiceLevel>Standard</ShipServiceLevel>
    <Address>
      <City>Beverly Hills</City>
      <State>CA</State>
      <PostalCode>90210-1234</PostalCode>
      <Country>US</Country>
    </Address>
  </FulfillmentData>
  <OrderItem>
    <ASIN>AmazonASIN </ASIN>
    <SKU> Internal-SKU</SKU>
    <ItemStatus>Pending</ItemStatus>
    <ProductName> This is the name of the product </ProductName>
    <Quantity>1</Quantity>
    <ItemPrice>
      <Component>
        <Type>Principal</Type>
        <Amount currency="USD">19.99</Amount>
      </Component>
    </ItemPrice>
  </OrderItem>
</Order>

    List<string> getNodes(string path, string nodeName) {

    List<string> nodes = new List<string>(); 

    XDocument xmlDoc = XDocument.Load(path); //Create the XML document type

    foreach (var el in xmlDoc.Descendants(nodeName)) {
            //for debugging
            //nodes.Add(el.Name + " " + el.Value);

            //for production
            nodes.Add(el.Value);
    }
   return nodes;
} //end getNodes

List<string> skuNodes = xml.getNodes(@"AmazonSalesOrders.xml", "SKU");