• c# 操作xml


    项目要求用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 “”;
    }
    }

  • 相关阅读:
    42 最大子数组Ⅱ
    笔试之const问题
    笔试中sizeof求字节数的问题
    40 用栈实现队列
    38 搜索二维矩阵Ⅱ
    25.Remove Nth Node From End of List(删除链表的倒数第n个节点)
    29.最小的K个数
    28.数组中出现次数超过一半的数字
    27.字符串的排列
    26.二叉搜索树与双向链表
  • 原文地址:https://www.cnblogs.com/liuzhengdao/p/1312773.html
Copyright © 2020-2023  润新知