Marc Howard
Marc Howard

Reputation: 425

How to read xml file c#

<CPT xmlns="http://www.example.org/genericClientProfile" xmlns:ns2="http://www.blahblah.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/genericClientProfile genericClientProfile.xsd">
  <header>
    <serviceId>CPT-UK</serviceId>
    <versionId>1.0</versionId>
    <brandCode>CUK</brandCode>
    <creationTime>2013-09-26T13:55:32.31+02:00</creationTime>
  </header>
</CPT>

I need to be able to read the elements in the header tag. I'm struggling to read the values for some reason, which i'm not sure of. What i've tried:

public ActionResult readxmldata()
    {
        using (var db = new CPTEntities())
        {
            var file = System.IO.Directory.GetFiles("C:\\Workspace\\CPTStaging","*.xml");

            foreach (var xmldoc in file)
            {
                XmlDocument docpath = new XmlDocument();
                docpath.Load(xmldoc);

                CPTPROFILE doc = new CPTPROFILE();
                db.SaveChanges();

                H_HEADER header = new H_HEADER();
                header.SERVICEID = docpath.SelectSingleNode("//CPT/header/@serviceId").Value;
                header.VERSIONID = Convert.ToDecimal(docpath.SelectSingleNode("//CPT/header/@versionId").Value);
                header.CREATIONTIME = Convert.ToDateTime(docpath.SelectSingleNode("//CPT/header/@creationTime").Value);
                header.BRANDCODE = docpath.SelectSingleNode("//CPT/header/@brandCode").Value;

                db.CPTPROFILEs.AddObject(doc);
                db.SaveChanges();
            }
        }

Upvotes: 0

Views: 103

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109547

For comparison, here is one way to do it with Linq-to-XML:

XDocument doc = XDocument.Load(xmlFileName);
XNamespace ns = "http://www.example.org/genericClientProfile";

var header = doc.Descendants(ns+"header").Single();

H_HEADER header = new H_HEADER();

header.SERVICEID    = (string)   header.Element(ns + "serviceId");
header.VERSIONID    = (double)   header.Element(ns + "versionId");
header.BRANDCODE    = (string)   header.Element(ns + "brandCode");
header.CREATIONTIME = (DateTime) header.Element(ns + "creationTime");

Upvotes: 2

Dmitriy Finozhenok
Dmitriy Finozhenok

Reputation: 854

Your XML uses namespaces. xmlns attribute declares default namespace. You should use it for each element of the XML.

XNamespace ns = "http://www.example.org/genericClientProfile";
XDocument doc = XDocument.Load(xmldoc);
XElement header = doc.Root.Element(ns + "header");

Upvotes: 3

Related Questions