Jameel Moideen
Jameel Moideen

Reputation: 7931

Get Child Nodes from an XML File

I have an XML File like below

<Attachment>
  <FileName>Perimeter SRS.docx</FileName>
  <FileSize>15572</FileSize>
  <ActivityName>ActivityNamePerimeter SRS.docx</ActivityName>
  <UserAlias>JameelM</UserAlias>
  <DocumentTransferId>7123eb83-d768-4a58-be46-0dfaf1297b97</DocumentTransferId>
  <EngagementName>EAuditEngagementNameNew</EngagementName>
  <Sender>[email protected]</Sender>
</Attachment>

I read these xml file like below

var doc = new XmlDocument();

doc.Load(files);

foreach (XmlElement pointCoord in doc.SelectNodes("/Attachment"))
{

}

I need to get each child node value inside the Attachment node. How can i get these xml elements from the xml node list?

Upvotes: 5

Views: 49907

Answers (3)

Faster Solutions
Faster Solutions

Reputation: 7005

var doc = new XmlDocument();

doc.Load(files);

foreach (XmlElement pointCoord in doc.SelectNodes("/Attachment"))
{
    if(pointCoord!=null)
    {
        var valueOfElement=pointCoord.InnerText;
    }
}

if you want to run conditional logic against the element names (UserAlias, etc) then use the Name property of the XmlElement.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

I need to get each child node value inside the Attachment node.

Your question is very unclear, but it looks like it's as simple as:

foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
}

After all, in the document you've shown us, the Attachment is the document element. No XPath is required.

As an aside, if you're using .NET 3.5 or higher, LINQ to XML is a much nicer XML API than the old DOM (XmlDocument etc) API.

Upvotes: 10

santosh singh
santosh singh

Reputation: 28642

try this

 var data = from item in doc.Descendants("Attachment")
             select new
             {
                  FileName= item.Element("FileName").Value,
                  FileSize= item.Element("FileSize").Value,
                  Sender= item.Element("Sender").Value
              };
 foreach (var p in data)
     Console.WriteLine(p.ToString());

Upvotes: 1

Related Questions