简体   繁体   中英

Getting Wrong Value Parsing XML in C#

Environment: VS 2010, .NET 3.5

I'm working on a project that pulls data from a RESTful web service. Almost all of it is working correctly except one section where it's getting incorrect values.

Here's a sample of the XML used in this part of the code:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<dataprovider>
  <id>DP6</id>
  <name>Query 1</name>
  <dataSourceId>96390</dataSourceId>
  <dataSourcePrefix>DS6</dataSourcePrefix>
  <updated>2014-08-25T16:51:38.000-04:00</updated>
  <duration>1</duration>
  <isPartial>false</isPartial>
  <rowCount>13</rowCount>
  <flowCount>1</flowCount>
  <dictionary>
    <expression qualification="Dimension" dataType="String">
      <id>DP6.DOa6</id>
      <name>City</name>
      <description>City located.</description>
      <dataSourceObjectId>DS6.DOa6</dataSourceObjectId>
      <formulaLanguageId>[City]</formulaLanguageId>
    </expression>
  </dictionary>
</dataprovider>

And here is the code:

private void loadElements(List<string> dps, int rptId)
{
  string name = string.Empty;
  string id = string.Empty;
  string elementUrl = baseUrl + string.Format(C_WEBI_URL, rptId) + C_DP_URL;
  foreach (string dpId in dps)
  {
    XmlDocument dpXml = getResponse(elementUrl + "/" + dpId);
    //get the Expression nodes that define the objects on the report
    XmlNodeList elementNodes = dpXml.SelectNodes("//expression");
    if (elementNodes != null)
    {
      foreach (XmlNode node in elementNodes)
      {
        id = node.SelectSingleNode("//dataSourceObjectId").InnerText;
        if (!elements.ContainsKey(id))
        {
          name = node.SelectSingleNode("//name").InnerText;
          elements.Add(id, name);
        }
      }
    }
  }
}

I expect to get a value of "DP6.DOa6" from the dataSourceObjectId, but it returns just "DP6". And I expect to get a value of "City" from the name, but it returns "Query 1". When I test the XPath with the above XML at http://www.xpathtester.com/xpath , I get the correct values, but it's not working in my code.

Any thoughts?

The problem with your name query is that the XmlNode object retains the outer xml as well so when you say //name it will return the first name element it finds in the document.

The correct xpath syntax will be name (no slashes).

As to the dataSourceObjectId my suspicion is that the . is causing this behavior perhaps try InnerXml instead of InnerText

Complete example:

foreach (XmlNode node in elementNodes)
  {
    id = node.SelectSingleNode("dataSourceObjectId").InnerXml; //I'm not sure if this will solve the problem.
    if (!elements.ContainsKey(id))
    {
      name = node.SelectSingleNode("name").InnerText;
      elements.Add(id, name);
    }
  }

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