0

Desired output

enter image description here

I am trying to read an xml doc using xpath. I am able to read the some elements but some not. I am trying to read this xml file and write this information in an excel file

I tried the following

    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();

 xmlDoc.Load("C:/Users/mypc/Documents/project/myfile.xml");
            XmlNode titleNode = xmlDoc.SelectSingleNode("//header");
            using (StreamWriter outputFile = new StreamWriter("C:/Users/myuser/Documents/project/WriteLines.txt"))
            {
                if (titleNode != null)
                    Console.WriteLine(titleNode.InnerText.ToString());
                outputFile.WriteLine(titleNode.InnerText);
            }
            Console.ReadKey();
        }
    }

My xml file looks like this

<header version="2.0">
    <phone>1234567</phone>
    <houseNumber>45</houseNumber>
    <date>2015-09-19</date>
    <deliveryId>12345696015</deliveryId>
  </header>

Is there any way I can read the children and write it in excel file ?

Leroi
  • 349
  • 4
  • 21

2 Answers2

0

Hope this code will help you.. {

        DataTable dt = new System.Data.DataTable();  
        dt.TableName = "Details";  
       dt.Columns.Add("phone", typeof(string));  
        dt.Columns.Add("houseNumber", typeof(string));  
         dt.Columns.Add("date", typeof(string));  
        dt.Columns.Add("deliveryId", typeof(string)); 

        dt.Rows.Add("1234567", "45","2015-09-19","KV12_3896096015");  


       //Create Temp directory to save xml file  
        var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());  
         Directory.CreateDirectory(tempDir);  
        string path = Path.Combine(tempDir, string.Format("{0}.{1}", "Prodcuts", "xml"));  
       //Write to xml file  
        dt.WriteXml(path, System.Data.XmlWriteMode.IgnoreSchema);  

        //Create HttpClient and MultipartFormDataContent  
        using (var client = new HttpClient())  
        using (var formData = new MultipartFormDataContent())  
        using (var fromFile=File.OpenRead(path))  
        {  

            formData.Add(new StringContent("Test"), "FileName");  
            formData.Add(new StringContent("xlsx"), "FileFormat");  
            formData.Add(new StreamContent(fromFile), "DataFile",Path.GetFileName(path));  
            //Call WebAPI  
            var response = client.PostAsync(webapiURL, formData).Result;  
            if (!response.IsSuccessStatusCode)  
            {  
                MessageBox.Show("Invalid response.");  
                return;  
            }  
            var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());  
            if (!Directory.Exists(tempPath))  
            {  
                Directory.CreateDirectory(tempPath);  
            }  
            //Save Excel file to Temp directory  

}

Sandy N
  • 85
  • 1
  • 6
0

Part 1 - iterating over child nodes

You've done pretty well finding the <header> element in the document using XPath. To extract information from individual child nodes just iterate over the ChildNodes collection using value of LocalName and InnerText properties of XmlNode for output like this:

foreach (XmlNode xmlNode in xmlDoc.SelectSingleNode("//header").ChildNodes)
{
    Console.WriteLine(xmlNode.LocalName + ", " + xmlNode.InnerText);
}

Note that //header XPath in combination with SelectSingleNode selects the first <header> element anywhere in the document. If the intent was to select the root node of the document then you should use /header, however selecting single root node isn't probably worth an XPath query.

Part 2 - output to MS Excel

I'd recommend you to pick some third party package to produce output in specific format. If you just need simple export for further processing, the easiest way is to produce a CSV file, which you can easily open in MS Excel:

using System.Linq;
// ...
var separator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
var output = xmlDoc.SelectSingleNode("//header").ChildNodes.Cast<XmlNode>()
    .Select(xmlNode => xmlNode.LocalName + separator + xmlNode.InnerText);
System.IO.File.WriteAllLines("output.csv", output);

Please note that this is a very simple solution. Proper solution would include some escaping of values on output.

Peter Wolf
  • 3,700
  • 1
  • 15
  • 30