1

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

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

或者

<xml>
<xdp:xdp>
...

可能吗?

4

2 回答 2

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 文档层次结构中任何位置是否存在任何节点。您可以轻松地从字符串或文件加载内容。

于 2012-12-24T08:08:28.967 回答
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");
于 2012-12-24T08:02:53.177 回答