2016-09-21 2 views
0

다음과 같이 XML이 있는데이 XML을 읽고 XML의 특정 요소를 가져 와서 Excel에 저장해야합니다. Expected ResultXML 읽기 및 Excel에 저장 C#

이 사람이 나를 안내 수 :

다음
<?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> 

가 예상 결과 : 다음은 내 XML 파일입니다.

+0

이것은 오픈 엑셀 파일처럼 보입니다. 당신은 xml의 일부만을 추출하고 엑셀로 저장하고 싶습니까? – jdweng

+0

예, XML의 일부를 추출하여 Excel에 저장하려고합니다. – ctee

답변

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

     } 

    } 

} 
+0

고마워요! 그 일은 내게 잘해. – ctee