2015-06-07 159 views
0

我從鏈接「http://www.codeproject.com/Tips/146237/Reading-XML-documents-using-LINQ」得到了一些啓示。用XML代碼擴展C#代碼

如果我需要檢索的Subject1Subject2數據,應該如何在新的C#是通過更換這個代碼listBox1.Items.Add(b.Element("Subject").Value.Trim());

C#:

var books = from nodes in System.Xml.Linq.XElement.Load("Books.xml").Elements("Book") select nodes; 

if (books != null) 
{ 
    foreach (var b in books) 
    { 
     listBox1.Items.Add(b.Element("Subject").Value.Trim()); 

    } 
} 

XML:

<?xml version="1.0" encoding="utf-8" ?> 
<Books> 
    <Book> 
    <Subject> 
    <Subject1>Subject1a</Subject1> 
    <Subject2>Subject1a</Subject2> 
    </Subject> 
    <Content> 
     History,Geography 
    </Content> 
    </Book> 

    <Book> 
    <Subject> 
    <Subject1>Subject2b</Subject1> 
    <Subject2>Subject2b</Subject2> 
    </Subject> 
    <Content> 
     Biology,Chemistry,Physics 
    </Content> 
    </Book> 
</Books> 

回答

1

我我不確定我是否正確理解你,

foreach (var b in books) { 
    var s = b.Element("Subject"); 
    listBox1.Items.Add(s.Element("Subject1").Value.Trim()); 
    listBox1.Items.Add(s.Element("Subject1").Value.Trim()); 
} 
+0

對象1&2不是書的直接子女,而是後裔 –

+0

@ChuckSavage你是對的,謝謝:) – user35443

0
var items = (from node in System.Xml.Linq.XElement.Parse(xml).Elements("Book") 
        let subject = node.Element("Subject") 
        select new 
        { 
         Subject1 = subject.Element("Subject1"), 
         Subject2 = subject.Element("Subject2") 

        }).ToList();