您的位置:首页 > 编程语言 > C#

C# 操作 XML 的方法(zz)

2010-03-05 17:03 393 查看
XmlDocument 例子
string filePath = HttpContext.Current.Server.MapPath("your.xml");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);

//取值
string xp = xmlDoc.SelectSingleNode("newTab").ChildNodes[0].InnerTex;

//给值
xmlDoc.SelectSingleNode("newTab").ChildNodes[0].InnerTex = "asdasd";
xmlDoc.Save(filePath);

XPathDocument 例子
XPathDocument doc=new XPathDocument("d:/test.xml");
XPathNavigator nav=doc.CreateNavigator();
XPathExpression exp=nav.Compile("//MenuItem");
exp.AddSort("@order",XmlSortOrder.Ascending,XmlCaseOrder.None,"",XmlDataType.Number);
XPathNodeIterator itr=nav.Select(exp);
while(itr.MoveNext())
{
Console.WriteLine(itr.Current.GetAttribute("order",""));
}

用xpath:
m_strServer = doc.SelectSingleNode(@"//根节点/子节点/Server").ChildNodes[0].InnerText;

关于空值的判断
SelectSingleNode()参数错误。
参数格式如楼上所示。另外你一行的代码太长,而且不判断。崩溃太正常了。
XmlNode node = doc.SelectSingleNode(@"//Configure/Server");
if(node != null)
m_strServer = node.InnerText;
else
...

xml修改的一个例子
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("a.xml");
XmlNode root=xmlDoc.SelectSingleNode("当前用户");
XmlElement xe1=xmlDoc.CreateElement("帐号");
xe1.InnerText="adv4";
root.AppendChild(xe1);
xmlDoc.Save("a.xml");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: