2012-11-11 2 views
0

XML 문서를 쿼리하려고하는데이 코드는 닫힌 태그 표기법으로 xml 파트를 읽지 않지만 정밀한 xelement를 읽습니다. 아무도 내가 잘못하고있는 것을 발견 할 수 있습니까? 당신이 XElements에 루프에 필요한 있도록, XElementCourse 및 다른 속성을 추가 한 이후XML 문서 쿼리

<?xml version="1.0" encoding="utf-8" ?> 
<Student> 

<Person name="John" city="Auckland" country="NZ" /> 

<Person> 
    <Course>GDICT-CN</Course> 
    <Level>7</Level> 
    <Credit>120</Credit> 
    <Date>129971035565221298</Date> 
</Person> 
<Person> 
    <Course>GDICT-CN</Course> 
    <Level>7</Level> 
    <Credit>120</Credit> 
    <Date>129971036040828501</Date> 
</Person> 
</Student> 
class Program 
{ 
    static void Main(string[] args) 
    { 
     XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml"); 
     IEnumerable<XElement> rows = from row in xDoc.Descendants("Person") select row; 

     foreach(XElement xEle in rows) 
     { 
     IEnumerable<XAttribute>attlist = from att in xEle.DescendantsAndSelf().Attributes() select att; 

      foreach(XAttribute xatt in attlist) 
      { 
      Console.WriteLine(xatt); 
      } 
      Console.WriteLine("-------------------------------------------"); 
     } 
     Console.ReadLine(); 

    } 
} 

답변

0

나는 프로그램이 따라서는 지금 문제 폐쇄 태그 파일을 제공 XML 문서를 생성 한

.. 속성 대신 -

foreach (XElement xEle in rows) 
{ 
    IEnumerable<XAttribute> attlist = from att in xEle.DescendantsAndSelf() 
             .Attributes() select att; 

    foreach (XAttribute xatt in attlist) 
    { 
     Console.WriteLine(xatt); 
    } 
    foreach (XElement elemnt in xEle.Descendants()) 
    { 
     Console.WriteLine(elemnt.Value); 
    } 
    Console.WriteLine("-------------------------------------------"); 
} 
+0

매력이있는 것처럼 작동합니다. 내가 만든 차이점을 이해하려고합니다. 괜찮 으면 나에게 브리핑 해 줄 수 있습니까? 감사합니다. –

+0

'XAttribute'는 속성을위한 반면'XElement'는 자식 노드를 위해 사용됩니다. 첫 번째 줄에서는 '이름', '도시'및 '국가'를 속성으로 선언했습니다. 그러나 다음 두 행에서 자식 노드를 만들었습니다. 자식 노드를 사용하면 값을 얻기 위해'Descendants' 컬렉션을 반복해야합니다. –

+0

감사합니다. 아래 값을 필터링하려면 아래 필터 코드를 사용하여 자식 요소 값을 가져올 수 없습니다. IEnumerable rows = xDoc.Descendants ("Person")의 행 from where (string) row.Attribute ("Level") == "7" 행 선택; –

0

먼저 사용자 수준으로 이동 한 다음 사람을 반복해야합니다. 그런 다음 각 사람에 대해 반복 할 수 있습니다. 그 속성을 보아라.

private static void Main(string[] args) 
    { 
     //string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 
     //XDocument xDoc = XDocument.Load(path + "\\Student Data\\data.xml"); 
     XDocument xDoc = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "Customers.xml"); 
     IEnumerable<XElement> xElements = xDoc.Descendants("Person"); 
     foreach (XElement element in xElements) 
     { 
      foreach (XAttribute attribute in element.Attributes()) 
      { 
       Console.WriteLine(attribute); 
      } 
      Console.WriteLine("-------------------------------------------"); 
     } 
     Console.ReadLine(); 
    }