-1

I am making an API call to a service, and receiving an big XML back. I am looking to grab the unique info that is attached to a header, but cannot find out how to do it.

XML call -

<InvDetailRequest>
    <InvDetailRequestHeader invDate="2023-06-14T18:51:50-04:00" invID="IN305">

I want to grab the InvDate, and the InvID, but do not know how.

In another part of my code, I am using this loop to grab all the ID's attached. But grabbing the singleNode inner text does not work.

XmlDocument doc = context.Data.ToXmlDocument();

XmlNodeList nodes = doc.DocumentElement.SelectNodes("/DataRequest/Source/AttachmentInfo/Attachment");
foreach (XmlNode node in nodes)  
{
    //Grab single node here - node.SelectSingleNode("ID").InnerText
}

I was able to get some ouput with

doc.DocumentElement.SelectSingleNode("//InvDetailRequest").InnerXml)

But I do not know how to single down the specific InvID variable to assign elsewhere.

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Phantom
  • 13
  • 5
  • You have to post the real XML , not just one line and post the whole code you have tried already and what is the problem and with line of code. – Serge Jun 16 '23 at 14:34
  • `invDate` and `invID` arn't nodes they are attributes of a node, so when you have the node call `node.Attributes["invDate"]` - https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlnode.attributes?view=net-7.0 - https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlattributecollection.itemof?view=net-7.0#system-xml-xmlattributecollection-itemof(system-string) – Rand Random Jun 16 '23 at 14:36
  • isn't it rather obvious, why your first code sample fails? this `"/DataRequest/Source/AttachmentInfo/Attachment"` seems to have nothing to do with the xml structure you have provided `InvDetailRequest/InvDetailRequestHeader` ?!? – Rand Random Jun 16 '23 at 14:37
  • @Serge the whole xml is about 800 lines long, Ill edit it to increase what I show by a bit. I just didnt wanna info overload – Phantom Jun 16 '23 at 14:38
  • 1
    @RandRandom sorry for the confusion, that /datarequest example is from another part of the code. The solution to my problem was the node.Attributes["Variable"]. I did not know that was considered an attribute, and not a node. thank you! – Phantom Jun 16 '23 at 14:41
  • @Phantom But at least you have to post a valid version – Serge Jun 16 '23 at 14:47

1 Answers1

0

if you are able to fix your xml, you can use this code

var result = XDocument.Parse(xml).Root
      .Descendants()   // or .Descendants("InvDetailRequestHeader")
      .Select(e => new { invDate = e.Attribute("invDate").Value, 
                         invID = e.Attribute("invID").Value })
      .FirstOrDefault();   // or ToList()
Serge
  • 40,935
  • 4
  • 18
  • 45