我想使用XElement來找出屬性Id的父節點。見下面的例子 這是我的數據..Linq to xml:找出父母?
<Data>
<Description>MASTER</Description>
<Data>
<Description>Parent1</Description>
<Data id="GUID1" Description="THIS IS A TEST" />
<Data id="GUID2" Description="THIS IS A TEST" />
<Data id="GUID3" Description="THIS IS A TEST" />
</Data>
<Data>
<Description>Parent2</Description>
<Data id="GUID4" Description="THIS IS A TEST" />
<Data id="GUID5" Description="THIS IS A TEST" />
</Data>
<Data id="GUID6" Description="THIS IS A TEST" />
</Data>
如果我想找出「GUID6」和「GUID1」父母的結果將是GUID6 =「MASTER」 和GUID1 =「MASTERParent1」,但我的結果不正確。請有人可以幫助我。
我也希望可以將輸出爲「MASTER.Parent1」所以它通過使用「點」
這裏分割了主,父是我的代碼
protected void Page_Load(object sender, EventArgs e)
{
var s = "<Data><Description>MASTER</Description><Data><Description>PARENT1</Description><Data id=\"GUID1\" Description=\"THIS IS A TEST\" /><Data id=\"GUID2\" Description=\"THIS IS A TEST\" /><Data id=\"GUID3\" Description=\"THIS IS A TEST\" /></Data><Data><Description>PARENT2</Description><Data id=\"GUID4\" Description=\"THIS IS A TEST\" /><Data id=\"GUID5\" Description=\"THIS IS A TEST\" /></Data><Data id=\"GUID6\" Description=\"THIS IS A TEST\" /></Data>";
var doc = XElement.Load(new StringReader(s));
var result = (from data in doc.Descendants("Data").Where(x => x.Attribute("id") != null)
select new
{
Id = data.Attribute("id").Value,
Decription = data.Attribute("Description").Value,
Parent = data.Parent.Value
}).ToList();
}
爲什麼'Parent2'是父母對GUID6? – sll 2012-02-24 15:01:06
斑點。你對錯了它的「主人」我已經更新了 – user929153 2012-02-24 15:07:03