读书人

求教怎样用 XDocument的XElement表达树

发布时间: 2013-01-26 13:47:04 作者: rapoo

求教怎样用 XDocument的XElement表达树
怎样用 XDocument的XElement表达树
[解决办法]
我总结的一些用法

//加载一个现有XML 可用 XElement.Load 修改文件可以用XElement.Save
//创建一个xml元素
var testXele = new XElement("国家", "中国");
testXele.Add(new XElement("江苏", new XText("我是江苏人"),
new XAttribute("color", "red")));
//将之前创建的xml增加到新元素中
XElement xmlTree = new XElement("Root2",
new XElement("国家", new XText("日本鬼子"), new XAttribute("color", "white")),
new XElement("国家", new XText("日本鬼子"), new XAttribute("color", "red")),
new XElement("国家", new XText("美国人"), new XAttribute("color", "yellow")),
testXele
);

//将元素填充到xml文档中
XDocument xDoc = new XDocument(xmlTree);
string s = xDoc.ToString();

根据据上面代码我们得到S结果如下
<Root2>
<国家 color="white">日本鬼子</国家>
<国家 color="red">日本鬼子</国家>
<国家 color="yellow">美国人</国家>
<国家>中国<江苏 color="red">我是江苏人</江苏></国家>
</Root2>




//获取国家元素节点集
IEnumerable<XElement> countries = xDoc.Elements().Descendants("国家");

//查出白色的日本鬼子元素
IEnumerable<XElement> whitejapan = (from c in countries where (string)c.Attribute("color") == "white" select c);
s = xDoc.ToString();
foreach (XElement r in whitejapan)
{
Response.Write(string.Format("<br/> 节点名称:{0} 值:{1} 属性:{2}", r.Name, r.Value, (string)r.Attribute("color") + "<br/>"));
}

Response出的结果
节点名称:国家 值:日本鬼子 属性:white


//删除查询出来的白色日本鬼子
whitejapan.Remove();

//修改红色日本鬼子
IEnumerable<XElement> redjapan = (from c in countries where (string)c.Attribute("color") == "red" select c);
foreach (var r in redjapan)
{


r.SetValue ("日本人");
r.SetAttributeValue("color","white");
}
s = xDoc.ToString();

读书人网 >.NET

热点推荐