繁体   English   中英

如何读取XML文件C#

[英]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>

我需要能够读取header标记中的元素。 由于某种原因,我正在努力读取值,我不确定。 我试过的

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

您的XML使用名称空间。 xmlns属性声明默认名称空间。 您应该将其用于XML的每个元素。

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

为了进行比较,这是使用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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM