當沒有更多孩子時,如何在XDocument
中獲得Node
的價值?獲取沒有孩子的XElements的價值
<Contacts>
<Company>
<Name>Testing</Name>
<ID>123</ID>
</Company>
</Contacts>
在這種情況下,我想拿到<Name>
和<ID>
元素的值,因爲沒有在他們的子元素。
我想後續
protected void LeXMLNode(HttpPostedFile file)
{
XmlReader rdr = XmlReader.Create(file.FileName);
XDocument doc2 = XDocument.Load(rdr);
foreach (var name in doc2.Root.DescendantNodes().OfType<XElement>().Select(x => x.Name).Distinct())
{
XElement Contact = (from xml2 in doc2.Descendants(name.ToString())
where xml2.Descendants(name.ToString()).Count() == 0
select xml2).FirstOrDefault();
string nome = name.ToString();
}
}
但沒有成功,因爲我的foreach傳中所有Elements
,我想獲得做到這一點不是有孩子的的的Elements
值。
一旦你的姓名和ID的元素,你應該使用的XElement的Value屬性檢索元素文本http://msdn.microsoft.com/en-us/library /system.xml.linq.xelement.value.aspx – 2012-08-06 20:46:18