刘政道 - 应用程序框架

《31天学会CRM项目开发(C#编程入门及项目实战)》作者,IT经理,程序员
  博客园  :: 新随笔  :: 联系 :: 管理

c# 操作xml

Posted on 2008-10-16 16:36  刘政道  阅读(343)  评论(2)    收藏  举报

项目要求用xml保存条目数据。

string str = “<root><listitem id="”11"”><no>1ff1</no><title>title</title><miji>miji</miji><author>author</author></listitem><listitem id="”1"”><no>1221</no><title>title</title><miji>miji</miji><author>hahahhahahah</author></listitem><listitem id="”2"”><no>ddd</no><title>title</title><miji>ddd</miji><author>author_daiqianjie</author></listitem></root>”;

构造xml

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

新增一个节点

/*
XmlNode root = doc.SelectSingleNode(”root”);
XmlElement ele = doc.CreateElement(”listitem”);
ele.SetAttribute(”id”,”3″);
XmlElement subEle = doc.CreateElement(”no”);
subEle.InnerText = “ddd”;
ele.AppendChild(subEle);
subEle = doc.CreateElement(”title”);
subEle.InnerText = “title”;
ele.AppendChild(subEle);
subEle = doc.CreateElement(”miji”);
subEle.InnerText = “ddd”;
ele.AppendChild(subEle);
subEle = doc.CreateElement(”author”);
subEle.InnerText = “author_daiqianjie”;
ele.AppendChild(subEle);
root.AppendChild(ele);

w(doc.InnerXml);
*/

删除一个节点

foreach (XmlNode node in doc.SelectNodes(”root/listitem”))
{
if (node.Attributes["id"].Value == “11″)
doc.SelectSingleNode(”root”).RemoveChild(node);
}
w(doc.InnerXml);

用xpath选择一个节点并输出值

//XmlNode node = doc.SelectSingleNode(”root/listitem[@id='2']“);
//w(node.SelectSingleNode(”author”).InnerText);

表格化显示xml

private string showXml(string str)
{
try
{
string r = “”;
if (str != “”)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
XmlNode root = doc.SelectSingleNode(”root”);

r += “<table width="”100%"” style=’border-bottom: 1px dotted #666666′>"n”;
r += “<tr style=’font-weight:bold;background-color:#E5F0FF;’>"n”;
r += “<td>档号</td>"n”;
r += “<td>题名</td>"n”;
r += “<td>密级</td>"n”;
r += “<td>责任者</td>"n”;
r += “</tr>"n”;
foreach (XmlNode node in root.ChildNodes)
{
r += “<tr>"n”;
r += “<td nowrap>” + node.SelectSingleNode(”no”).InnerText + “</td>"n”;
r += “<td nowrap>” + node.SelectSingleNode(”title”).InnerText + “</td>"n”;
r += “<td nowrap>” + node.SelectSingleNode(”miji”).InnerText + “</td>"n”;
r += “<td nowrap>” + node.SelectSingleNode(”author”).InnerText + “</td>"n”;
r += “</tr>"n”;
}
r += “</table>"n”;
}
return r;
}
catch (Exception ex)
{
logs(ex.ToString());
return “”;
}
}