【问题标题】:Reading XML and Save into Excel C#读取 XML 并保存到 Excel C#
【发布时间】:2016-09-21 14:24:16
【问题描述】:

我有如下的 XML,我需要阅读这个 XML 并获取 XML 中的特定元素并保存到 excel 中。 下面是我的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<ns1:BookTestXMLExport StartTime="2016-09-20T12:58:15.000+07:00" scanTime="2016-09-20T12:58:15.000+07:00" scanStatus="Pass">
    <ns1:MachineXML barCode="ISN-1000500213" Revision="2016A" bookType="Novel"/>
    <ns1:StationXML scannerName="HP4512745" stage="v810"/>
    <ns1:ScanXML name="32:2:165:1">
        <ns1:IndictmentXML algorithm="NIL" subType="17X8X15MM" imageFileName="175228000_9_0.jpg">
            <ns1:BorrowXML packageId="NIL" userId="NIL" name="NIL"/>
            <ns1:BookXML name="GrayDay" desc="Love Story"/>
        </ns1:IndictmentXML>
    </ns1:ScanXML>
    <ns1:ScanXML name="35:23:165:1">
        <ns1:IndictmentXML algorithm="NIL" subType="17X8X15MM" imageFileName="175228001_9_0.jpg">
            <ns1:BorrowXML packageId="NIL" userId="8799" name="Sharon"/>
            <ns1:BookXML name="Harry Potter" desc="Magic"/>
        </ns1:IndictmentXML>
    </ns1:ScanXML>
</ns1:BookTestXMLExport>

以下是预期结果: Expected Result

谁能指导我。

【问题讨论】:

  • 这看起来像打开的 excel 文件。您只想提取部分 xml 并保存到 excel 中?
  • 是的,我想提取一部分xml并保存到excel中

标签: c# xml excel extract


【解决方案1】:

试试这个来解析文件。还是需要另存为excel。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication14
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement bookTestXMLExport = doc.Descendants().Where(x => x.Name.LocalName == "BookTestXMLExport").FirstOrDefault();
            XNamespace ns = bookTestXMLExport.GetNamespaceOfPrefix("ns1");

            var results = doc.Descendants(ns + "BookTestXMLExport").Select(x => new
            {
                scanStatus = (string)x.Attribute("scanStatus"),
                barCode = (string)x.Element(ns + "MachineXML").Attribute("barCode"),
                ScanXML = x.Elements(ns + "ScanXML").Select( y => new {
                    name = (string)y.Descendants(ns + "BookXML").FirstOrDefault().Attribute("name"),
                    desc = (string)y.Descendants(ns + "BookXML").FirstOrDefault().Attribute("desc")
                }).ToList()
            }).ToList();

        }

    }

}

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多