簡體   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