I have a problem with reading variables inside of an XML-file in C#.
I have the following XML-File:
<?xml version="1.0" encoding="utf-8"?>
<list xmlns:xsd=...>
<row id="2b7bed1a-bd72-4e83-9b69-26c05cce6379">
<hostname>TestName1</hostname>
<outputs>
<outputId>HL7 Output</outputId>
</outputs>
</row>
<row ...
</row>
</list>
I m trying here to write a code, which reads the XML-File and with use of a loop get the id of each hostname.
I already wrote the following part, which loads the xml-file. Can someone help me to complete this?
var xmlFile = @"C:\Users\vosoughi-m\Desktop\output_mapping.xml";
var doc = new XmlDocument();
doc.Load(xmlFile);
Thanks in advance
EDIT:
I Would like to have the following output:
Hostname: TestName1
ID: 2b7bed1a-hd72-4e83-9b69-66c05cce6379
Hostname: TestName2
ID: ce4372d3-453e-4ed8-ba60-6694a2680c24
...
CodePudding user response:
Use xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication21
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("row")
.Select(x => new { id = (string)x.Attribute("id"), hostname = (string)x.Element("hostname") }).ToList();
}
}
}