2014-06-06 4 views
0

아래 XML에서 중첩 된 요소를 읽으려고합니다. 지금까지 나는 chantier/data 요소의 데이터를 읽을 수 있었지만 이제는 <questions><sitePreparation> and <ctm> 내부의 데이터를 어떻게 읽을 수 있습니까? Xml 파일과 코드는 너무 길기 때문에 약간 단락되었습니다. 어떤 도움이라도 대단히 감사합니다. 읽기 questions 요소의Linq to xml을 사용하여 중첩 된 요소를 읽는 방법

<?xml version="1.0" encoding="UTF-8"?> 
<Audit> 
    <controls> 
     <guid> 
      0001 
     </guid> 
     <templateVersion> 
        1.0 
     </templateVersion> 
    </controls> 
    <chantier> 
     <data> 
      <V2>V2</V2> 
      <V3>V3</V3> 
      <V3_1>V3_1</V3_1> 
      <V4>V4</V4> 
      <oresTiersPanel> 
       <S1_2>S1_2</S1_2> 
      </oresTiersPanel> 
      <agentsTiersPanel> 
       <S1_2_2>S1_2_2</S1_2_2> 
      </agentsTiersPanel> 
     </data> 
     <questions> 
      <sitePreparation> 
       <P1_Question>P1_Q</P1_Question> 
       <P6_Question>P6_Q</P6_Question> 
      </sitePreparation> 
      <ctm> 
       <C1_Question>C1_Q</C1_Question> 
       <C2_Question>C2_Q</C2_Question> 
       <C2_1>C2_1</C2_1> 
      </ctm> 
     </questions> 
    </chantier> 
</Audit> 

private static void ReadXml() 
{ 
    XDocument xdoc = XDocument.Load("sipp.xml"); 

    if (xdoc.Root != null) 
    { 
     var chantier = from ch in xdoc.Root.Elements("chantier").Elements("data") 
         let agentsTiersPanel = ch.Element("agentsTiersPanel") 
         where agentsTiersPanel != null 
         select new 
      { 
       v2 = (string)ch.Element("V2"), 
       v3 = (string)ch.Element("V3"), 
       v3_1 = (string)ch.Element("V3_1"), 
       v4 = (string)ch.Element("V4"), 
       S1_2_2 = (string)agentsTiersPanel.Element("S1_2_2"), 
       S1_2_2_1 = (string)agentsTiersPanel.Element("S1_2_2_1"), 
       S1_2_3 = (string)agentsTiersPanel.Element("S1_2_3"), 
       S3 = (string)ch.Element("S3"), 
       S3_1 = (string)ch.Element("S3_1"), 
       P1_Question = (string)ch.Element("P1_Question") 
      }; 

     foreach (var item in chantier) 
     { 
      Console.WriteLine(item.v2 + " " + item.v3); 
     } 
    } 
} 
+0

어떻게 데이터를 읽습니까 강력한 형식의 객체로 작업 할 수 있습니다? –

+0

다음 질문을 자세히 검토하십시오. http://stackoverflow.com/questions/13203975/how-to-parse-deeply-nested-using-linq-to-xml, http://stackoverflow.com/questions/11758904/accessing- 중첩 된 요소를 통해 linq - to - XML ​​... 희망이 도움이 .. 건배! –

+0

괜찮아요. 질문을 읽는 데있어서 당신의 문제는 무엇입니까? 동일한 접근 방식을 사용하십시오 –

답변

0

샘플 : 당신이 당신의 익명 객체의 일부로 P1 및 P6 질문을 반환하려는 경우

var questions = xdoc.Root.Elements("chantier") 
        .Elements("questions").FirstOrDefault(); 

if (questions != null) 
{ 
    var sitePreparation = questions.Element("sitePreparation"); 
    if (sitePreparation != null) 
    { 
     Console.WriteLine((string)sitePreparation.Element("P1_Question")); 
     Console.WriteLine((string)sitePreparation.Element("P6_Question")); 
    } 
} 

, 다음 ch이 인 것을 염두에 두어야 data 요소는 chantier이 아니라 chantier 요소 자체입니다. 그래서 ch.Element("P1_Question")null을 반환합니다. null 요소 쿼리를 건너 뛰는으로 보일 것 같은 :

var chantiers = 
    from chantier in xdoc.Root.Elements("chantier") 
    let data = chantier.Element("data") 
    let questions = chantier.Element("questions") 
    where data != null && questions != null 
    select new { 
     V2 = (string)data.Element("V2"), 
     V3 = (string)data.Element("V3"), 
     V3_1 = (string)data.Element("V3_1"), 
     V4 = (string)data.Element("V4"), 
     S1_2_2 = (string)data.Element("agentsTiersPanel").Element("S1_2_2"), 
     P1_Question = (string)questions.Element("sitePreparation") 
            .Element("P1_Question") 
    }; 

출력 :

[ 
    { 
    V2: "V2", 
    V3: "V3", 
    V3_1: "V3_1", 
    V4: "V4", 
    S1_2_2: "S1_2_2", 
    P1_Question: "P1_Q" 
    } 
] 
+0

두 번째 루프를 만들지 않고 첫 번째 루프의 요소를 읽을 수 있습니까? 요소 위로 이동 한 다음 올바른 요소로 이동하는 것이 가능한지 알고 싶습니다. –

+1

감사합니다. 세르게이, 당신의 예가 Linq이 XML을 읽는 방법을 이해하는 데 도움이되었습니다. –

1

객체로 역 직렬화하는 것이 더 쉬울 수 있습니다. VS 내에서 Paste special 기능을 사용하여 XML 구조의 클래스 표현을 가져올 수 있습니다. 거기에서, 그것은 직렬화 복원을 끝까지 매우 간단합니다 :

private Audit GetAuditNodes() 
{ 
    Audit audit = null; 
    XmlSerializer serializer = new XmlSerializer(typeof(Audit)); 
    string uri = "data.xml"; 

    try 
    { 
     XmlReaderSettings settings = new XmlReaderSettings(); 
     settings.CheckCharacters = false; 
     settings.CloseInput = true; 
     settings.DtdProcessing = DtdProcessing.Ignore; 
     settings.IgnoreComments = true; 
     settings.IgnoreWhitespace = true; 

     using (XmlReader reader = XmlReader.Create(uri, settings)) 
     { 
      audit = (Audit)serializer.Deserialize(reader); 
     } 
    } 
    catch (Exception exc) 
    { 
     //log an error or something 
    } 

    return audit; 
} 

당신이 많은 청소기 코드가도`CHANTIER/data`에서

관련 문제