-2

Hi I've been working on this asp.net webform written on c# and i'm currently stock getting value on XML result encapsulated in a string. I know little about XML and here is my attemps.

i have this XML string

<Code>0</Code>
<responseData>
    <LotDetails>
        <DEVICE>OH503/E-ICAM</DEVICE>
        <DEVICE12NC>340000064194</DEVICE12NC>
        <CONTAINERNAME>MBP001012700</CONTAINERNAME>
        <PACKAGE>SOT1207</PACKAGE>
    </LotDetails>
</responseData>

and i need to get the value of <CONTAINERNAME> in c# i have this code

string result = tmpVal.GetQueryResult(System.Configuration.ConfigurationManager.AppSettings["queryname_CMSS"].ToString(), System.Configuration.ConfigurationManager.AppSettings["paramnames_CMSS"].ToString(), LotID).InnerXml.ToString();
     XmlDocument doc = new XmlDocument();
            doc.LoadXml(result);
            XmlNode idNode = doc.SelectSingleNode("//responseData/LotDetails/CONTAINERNAME");

My code above returns me an error of dditional information: There are multiple root elements. Line 1, position 16. It looks like i'm not getting the root element on my XML result. Would someone help me out with this? Thank you in advance. Hope you understand what i mean.

Berzerk25
  • 18
  • 8

1 Answers1

1

You can deserialize the xml that does not have a parent node like this,

    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<parent>" + result + "</parent>");
    //doc.LoadXml($"<parent>{result}</parent>");

    XmlNode idNode = doc.SelectSingleNode("//responseData/LotDetails/CONTAINERNAME");

Or you can use a method to Parse XML without a parent node.

Jawad
  • 11,028
  • 3
  • 24
  • 37
  • Use the + sign instead of $ sign to concatenate the string. – Jawad Jan 27 '20 at 00:21
  • Be aware that this won't work if the supplied XML includes an XML declaration or DOCTYPE declaration. – Michael Kay Jan 27 '20 at 00:24
  • Proper XML should have a parent node defined and in such case, this wouldnt be required. Since its a specific use-case, adding parent with two rootElements is being suggested. I totally agree with you @MichaelKay, If you are trying to work XML like this, you are most likely better off trying to get the source of XML corrected – Jawad Jan 27 '20 at 00:26
  • why im not getting the parent it suppose to be like this 0 OH503/E-ICAM 340000064194 MBP001012700 SOT1207 – Berzerk25 Jan 27 '20 at 00:36
  • The root cause problem is with the very first line: **string result = tmpVal.GetQueryResult(System.Configuration.ConfigurationManager.AppSettings["queryname_CMSS"].ToString(), System.Configuration.ConfigurationManager.AppSettings["paramnames_CMSS"].ToString(), LotID).InnerXml.ToString();** You need to get from the configuration file XML as XML data type, not the string. – Yitzhak Khabinsky Jan 27 '20 at 00:49