DocumentEntity="Borrower"|DataType="Table"|Value=" DocumentEntity="Borrower"|DataType="Table"|Value=" DocumentEntity="Borrower"|DataType="Table"|Value="

XML reading the nested nodes without xpath

45 Views Asked by At

I have following xml.

<?xml version="1.0"?>
<DataElement Name="Borrower">DocumentEntity="Borrower"|DataType="Table"|Value="
<Borrowers>
<Borrower1><Field1>Value="Value1"</Field1>
      <Field2>Value="Value2"</Field2>
</Borrower1>
<Borrower2>
        <Field1>Value="Value1"</Field1>
      <Field2>Value="Value2"</Field2>
</Borrower2>
</Borrowers>
"
</DataElement>

I am trying to get the value for DataElement Borrower in another xml so that i can use that to further read each of borrower nodes data.

i am using XmlDocument childnodes property to get the inside ones. But since this is a nested xml inside it again, i am unable to understand how to get this. Please help.

1

There are 1 best solutions below

0
D A On

I have fixed the XML in a way I think is making sense and I present you this solution:

   static void Main(string[] _)
   {
       string s = "<?xml version=\"1.0\"?>\r\n<DataElement Name=\"Borrower\">DocumentEntity=\"Borrower\"|DataType=\"Table\"|Value=\"\r\n<Borrowers>\r\n<Borrower1><Field1>Value=\"Value1\"</Field1>\r\n      <Field2>Value=\"Value2\"</Field2>\r\n</Borrower1>\r\n<Borrower2>\r\n        <Field1>Value=\"Value1\"</Field1>\r\n      <Field2>Value=\"Value2\"</Field2>\r\n</Borrower2>\r\n</Borrowers>\r\n\"\r\n</DataElement>";
                                   
       XDocument doc = XDocument.Parse(s);
       XElement root = doc.Root!;
       var borrowers = (from el in root.Elements("Borrowers")
                                          select el.Elements().ToList()).First().ToList();
       borrowers.ForEach(el =>
       {
           foreach (var item in el.Elements())            
               Console.WriteLine(el.Name + " - "+ item.Value.ToString());
       });
   }

I am using Linq to select the Borrowers and then I do a ForEach over each found Borrower and again a loop over the items of each Borrower.