2015-04-06 60 views
-6

XML文件數據如下給出我想更改c#中Urdu Book的Price節點的值。怎麼做!!!如何更改節點的值

<?xml version="1.0" encoding="utf-8"?> 
<Data> 
    <Product> 
     <Name>English Book</Name> 
     <Pieces>10</Pieces> 
     <RemainingPieces>5</RemainingPieces> 
     <Price>100</Price> 
    </Product> 
    <Product> 
     <Name>Urdu Book</Name> 
     <Pieces>20</Pieces> 
     <RemainingPieces>10</RemainingPieces> 
     <Price>1000</Price> 
    </Product> 
    <Product> 
     <Name>Grammar Book</Name> 
     <Pieces>20</Pieces> 
     <RemainingPieces>10</RemainingPieces> 
     <Price>1000</Price> 
    </Product> 
</Data> 
+2

做一個簡單的谷歌搜索'C#計算器如何更改XML file'萬噸互聯網 – MethodMan

+1

C#中的XML已多次和廣泛報道了許多地方從事工作的例子在那裏的節點值。像推薦的@MethodMan這樣粗略的Google搜索是一個很好的開始。請先嚐試一下,然後再回答一些關於*代碼*的更具體問題。 – tnw

回答

0

您可以嘗試使用LINQ to XML,因爲這:

var doc = XDocument.Load("book.xml"); 
doc.Element("Data") 
    .Element("Product") 
    .Element("Price") 
    .SetElementValue("value"); 
doc.Save("book_modified.xml"); 

About Linq to XML

沒有嘗試編譯,但應儘量接近。

0

如何處理你的xml這樣的事情?

DataSet ds = new DataSet(); 
byte[] strAsBytes = new System.Text.UTF8Encoding().GetBytes(strYourXml); 
System.IO.MemoryStream ms = new System.IO.MemoryStream(strAsBytes); 

ds.ReadXml(ms); 

string serach_name = "Urdu Book"; 
string new_value = 42; 

if ((ds.Tables("Product") != null)) { 

    foreach (DataRow t_row in ds.Tables("Product").Rows) { 
     if ((t_row("Name") == serach_name)) { 
      t_row("Price") = new_value; 
      break; 
     } 

    } 
}