2017-01-20 1 views
2

다음 XML을 가지고 있습니다. 데이터를 가져 오는 가장 좋은 방법은 무엇입니까?Linq에서 XML로 데이터를 가져 오는 방법은 무엇입니까?

<?xml version='1.0' encoding='UTF-8'?> 
<Root> 
    <EmployeeDataRoot> 
    <EmployeeData> 
     <Employee_id>123456</Employee_id> 
     <Employee_Status>A</Employee_Status> 
     <Business_Unit>EN00</Business_Unit> 
     <Cost_Center>0904/1992</Cost_Center> 
     <Work_Location>DFW</Work_Location> 
     <Location>DFW-HDQ1</Location> 
     <Job_Category>0003</Job_Category> 
     <Last_Name>John</Last_Name> 
     <First_Name>Doe</First_Name> 
     <Middle_Name /> 
     <Preferred_Name /> 
     <Position_Title>Programmer/Analyst</Position_Title> 
     <Legal_Entity>EN00</Legal_Entity> 
     <Department_Unit>IT HR &amp; Employee Technology</Department_Unit> 
     <Run_Date>2016-12-12</Run_Date> 
    </EmployeeData> 
    </EmployeeDataRoot> 
    <Footer_No_of_Records> 
    <Records>1</Records> 
    </Footer_No_of_Records> 
</Root> 

온라인 몇 가지 예를보고 한 후, 난의 특성을 통해 보았다이 두 반복을 시도했지만 에러를 대상

의 인스턴스로 설정되지

개체를 얻을 내 Employee 클래스와 철자가 틀린 노드는 보이지 않았습니다. 오류는 내가 XML을 올바르게 쿼리하지 않는다고 생각합니다.

var xDoc = XDocument.Load(file.FullName); 
listEmployee = 
    (from e in xDoc.Descendants("EmployeeData") 
     select new Employee 
     { 
     EmployeeID = e.Element("Employee_ID").Value, 
     EmployeeStatus = e.Element("Employee_Status").Value, 
     BusinessUnit = e.Element("Business_Unit").Value, 
     CostCenter = e.Element("Cost_Center").Value, 
     WorkLocation = e.Element("Work_Location").Value, 
     Location = e.Element("Location").Value, 
     JobCategory = e.Element("Job_Category").Value, 
     FirstName = e.Element("First_Name").Value, 
     LastName = e.Element("Last_Name").Value, 
     LegalEntity = e.Element("Legal_Entity").Value 
    } 
    ).ToList(); 

와 나는 또한

listEmployee = 
    (from e in xDoc.Element("Root").Elements("EmployeeDataRoot/EmployeeData") 
    select new Employee 
    { 
     EmployeeID = e.Element("Employee_ID").Value, 
     EmployeeStatus = e.Element("Employee_Status").Value, 
     BusinessUnit = e.Element("Business_Unit").Value, 
     CostCenter = e.Element("Cost_Center").Value, 
     WorkLocation = e.Element("Work_Location").Value, 
     Location = e.Element("Location").Value, 
     JobCategory = e.Element("Job_Category").Value, 
     FirstName = e.Element("First_Name").Value, 
     LastName = e.Element("Last_Name").Value, 
     LegalEntity = e.Element("Legal_Entity").Value           
    } 
).ToList(); 
+1

엘리먼트 이름이'Employee_id'이므로'e.Element ("Employee_ID")'는 null이라는 것을 알 수 있습니다. 'Element()'호출을 초기화 구문에 삽입하는 대신 별도의 줄에 넣으면 이러한 문제를 쉽게 디버그 할 수 있습니다. 또는 인라인 Null 검사를 추가하십시오 ('e.Element ("First_Name") == null? "": e.Element ("First_Name") .Value') –

답변

1

귀하의 시도, 바로 경악했지만, 당신이 쓰는 잘못 "employee_id입니다". 이것을 시도해보십시오 :

+0

네. 나는 그것이 철자가 틀린 무엇인가 있을지도 모른다라고 생각했고, 그들을 끝내었다. 그러나 물론 나는 그것을 놓쳤다. 그 여분의 눈을 찾아 주셔서 감사합니다. – Caverman

관련 문제