0
<AspResp errCode="NA" errMsg="NA" status="1" transId="6c8c5901-6119-4c59-89ce-b3f9efb141f2">
    <EResp errCode="NA" errMsg="NA" resCode="ea3229b1-c9ff-455b-8d3f-84a4c2384c85" status="1" ts="2020-04-27T15:00:10.947" txn="90f4f36f-7051-4c6d-bed4-bd717ddfa38d">
        <Signatures>
            <DocSignature error="NA" id="1">test</DocSignature>
        </Signatures>
    </EResp>
</AspResp>

I want value of transId from first node in the above XML.

I used this code but it is useless

foreach (XElement hashElement in doc.Descendants("transId"))
{
    hashValue = (string)hashElement;
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

1

Select required node. Since transId is an attribute, you should access like this:

string attrtransId  = node.Attributes["transId"].value
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Always_a_learner
  • 1,254
  • 1
  • 8
  • 16
  • I think this needs a bit more detail to be useful, it doesn't relate to the code in the original question. – mattbloke Apr 28 '20 at 10:51
0

Take a look at this, It's very detailed & easy to understand.

How do I read and parse an XML file in C#?

string XMLText = @"<AspResp errCode='NA' errMsg='NA' status='1' transId='6c8c5901-6119-4c59-89ce-b3f9efb141f2'><EResp errCode='NA' errMsg='NA' resCode='ea3229b1-c9ff-455b-8d3f-84a4c2384c85' status='1' ts='2020-04-27T15:00:10.947' txn='90f4f36f-7051-4c6d-bed4-bd717ddfa38d'><Signatures><DocSignature error='NA' id='1'>test</DocSignature></Signatures></EResp></AspResp>";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(XMLText);
        XmlNode node = doc.GetElementsByTagName("AspResp")[0];
        string transId = node.Attributes["transId"].Value;
KhanZeeshan
  • 1,410
  • 5
  • 23
  • 36
0

Tested xpath with http://xpather.com/2S8920tn

string XMLText =
            @"<AspResp errCode='NA' errMsg='NA' status='1' transId='6c8c5901-6119-4c59-89ce-b3f9efb141f2'><EResp errCode='NA' errMsg='NA' resCode='ea3229b1-c9ff-455b-8d3f-84a4c2384c85' status='1' ts='2020-04-27T15:00:10.947' txn='90f4f36f-7051-4c6d-bed4-bd717ddfa38d'><Signatures><DocSignature error='NA' id='1'>test</DocSignature></Signatures></EResp></AspResp>";
var doc = XDocument.Parse(XMLText);
string transId = doc.XPathSelectElement("/node()[1]").Attribute("transId")?.Value;
mattbloke
  • 1,028
  • 1
  • 12
  • 26