简体   繁体   中英

How to read specific XML values?

This is given XML:

<NewDataSet>
  <Table>
    <ProductCode>0120314</ProductCode>
    <SpecificationItemName>USB</SpecificationItemName>
    <SpecificationItemValues>&lt;Values xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;Value&gt;USB 2.0&lt;/Value&gt;&lt;/Values&gt;</SpecificationItemValues>
  </Table>
  <Table>
    <ProductCode>0987046</ProductCode>
    <SpecificationItemName>Other</SpecificationItemName>
    <SpecificationItemValues>&lt;Values xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;Value&gt;1 x PCIe 2.0 x16&lt;/Value&gt;&lt;Value&gt;2 x PCIe 2.0 x1&lt;/Value&gt;&lt;/Values&gt;</SpecificationItemValues>
  </Table>
</NewDataSet>

And this is my solution to read ProductCode, SpectificationItemName and complete value of SpecificationItemValues. Can you help me to read SpecificationItemValues by values (one by one, if more than one)? Thank you.

This is my code:

foreach (XmlNode nodeSpecification in xmlDokument.SelectSingleNode("//NewDataSet"))
{
    if (nodeSpecification.Name == "Table")
    {
        foreach (XmlNode nodeElements in nodeSpecification)
        {
            if (nodeElements.Name == "ProductCode")
            {
                MessageBox.Show(nodeElements.InnerText);
            }
            if (nodeElements.Name == "SpecificationItemName")
            {
                MessageBox.Show(nodeElements.InnerText);
            }
            if (nodeElements.Name == "SpecificationItemValues")
            {
                MessageBox.Show(nodeElements.InnerText);                          
            }
        } //you were missing a closing } by the way
    }
}

Thank you @Sam.C and @Amir Sasson. With your help find complete soulution.

if (cvorElementi.Name == "SpecificationItemValues")
{
var xmlValues = System.Net.WebUtility.HtmlDecode(cvorElementi.InnerText);
    XmlDocument valuesDoc = new XmlDocument();
    valuesDoc.LoadXml(xmlValues);

    foreach (XmlNode valuesNode in valuesDoc.SelectSingleNode("//Values"))
    {
        if (valuesNode.Name=="Value")
            {
             MessageBox.Show(valuesNode.InnerText);
            }
    }
}                               

Like this:
on the SpecificationItemValues Node:

var xmlValues = System.Web.HttpUtility.HtmlDecode(nodeElements.InnerText);
//you might want to use System.Net.WebUtility.HtmlDecode instead to avoid System.Web
XmlDocument valuesDoc = new XmlDocument();
valuesDoc .LoadXml(xmlValues );
var vals = valuesDoc.SelectNodes("//Value");
//Here You Can iterate on vals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM