Asp.net 修改Xml文檔中的資料

來源:互聯網
上載者:User

修改Xml文檔中的資料:
一:使用XPathNavigator修改xml資料
////獲得dom對象
XmlDocument doc = new XmlDocument();
//載入xml文檔
doc.Load(Server.MapPath("~//Xml//Mark.xml"));
//擷取XPathNavigator對象
XPathNavigator navigator = doc.CreateNavigator();
//找到Id屬性等於markValue的節點
string path = @"//*[@id='" + markValue + "']";

foreach (XPathNavigator nav in navigator.Select(path))
{
    //移到當前節點的第一個子節點
    nav.MoveToFirstChild();
    //修改當前節點的值
    int mark = nav.ValueAsInt;
    mark++;
    nav.SetValue(mark.ToString());
}
//儲存修改到原來的檔案
doc.Save(Server.MapPath("~//Xml//Mark.xml"));

二:使用Dom修改xml資料

//XmlElement和XmlNode的區別:
//XmlNode 是抽象類別 XmlElement繼承自XmlNode類
//在一個xml文檔中,
//每一個單獨的節點都是一個XmlElement,也是一個XmlNode
//但對於XmlElement而言:它是單獨的,是只擁有“屬性”的一個節點
//而不存在子項目之說
//而XmlNode則是處在“一棵樹”的大環境中,它有自己的屬性,
//也有與他關聯的子節點,父節點等;

1.使用XmlElement
//獲得dom對象
XmlDocument doc = new XmlDocument();
//載入xml文檔
doc.Load(Server.MapPath("~//Xml//Mark.xml"));
//擷取xml文檔根節點
XmlElement root = doc.DocumentElement;
//找到Id屬性等於markValue的節點
string path = @"//*[@id='" + markValue + "']";
foreach (XmlNode node in root.SelectNodes(path))
{
   XmlElement ele = node.FirstChild as XmlElement;
   int mark = int.Parse(ele.InnerText);
   mark++;
   ele.Value = mark.ToString();
}
//儲存修改到原來的檔案
doc.Save(Server.MapPath("~//Xml//Mark.xml"));

2.使用XmlNode
//獲得dom對象
XmlDocument doc = new XmlDocument();
//載入xml文檔
doc.Load(Server.MapPath("~//Xml//Mark.xml"));
//擷取xml文檔根節點
XmlElement root = doc.DocumentElement;
//找到Id屬性等於markValue的節點
string path = @"//*[@id='" + markValue + "']";
foreach (XmlNode node in root.SelectNodes(path))
{
   //一:使用XmlNode對象找到我們需要的文本資料
   //有兩種方法:
   //1.在元素節點層級尋找:node.InnerText
   //2.在文本節點層級尋找:node.Value 或者 node.InnerText

   //通過元素節點的方法
   //如果是node.FirstChild.Value 它的值會等於null
   //因為實際上它表示的是它的下一級子節點對象:文本節點對象
   //而不是一段文本值
   //所以如果是想在元素節點上就修改改元素的文本值
   //需要使用node.FirstChild.InnerText屬性
   int mark = int.Parse(node.FirstChild.InnerText);
   mark++;
   node.FirstChild.InnerText = mark.ToString();

   //通過文本節點的方法
   //直接找到節點的最底部,也就是文本節點
   //此時node.Value才是需要的文本資料
   XmlNode xn = node.FirstChild.FirstChild;
   int mark = int.Parse(xn.Value);
   mark++;
   xn.Value = mark.ToString();
}
//儲存修改到原來的檔案
doc.Save(Server.MapPath("~//Xml//Mark.xml"));

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.