0
<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();
            }
        }
1

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

Comments

2

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");

3 Comments

Thank you! I didn't realise you had to declare the namespace to access the attributes.
What if i have an element like this: <section xmlns="" id="fc105706-2fbe-410c-92bb-c46b723b7e17" name="globalClientFacts"> Do i need to have both the namespace and "" ?
@MarcHoward Hmm I'm not sure I'm afraid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.