[英]how to get and edit specific value of xml
是否有可能通過使用asp.c#獲取和編輯xml的特定值? 例如,我的xml文件:
<posters>
<poster>
<quantity>100</quantity>
<stock>100</stock>
<price>88</price>
</poster>
<poster>
<quantity>100</quantity>
<stock>150</stock>
<price>95</price>
</poster>
<poster>
<quantity>200</quantity>
<stock>100</stock>
<price>95</price>
</poster>
<poster>
<quantity>200</quantity>
<stock>150</stock>
<price>100</price>
</poster>
</posters>
數量== 200和存貨== 100且數量== 100和存貨== 150中有兩個95。我可以僅從數量== 200和存貨== 100中獲取值95並對其進行編輯,而無需從中修改相同的95數量== 100&庫存== 150?
我嘗試使用“ SelectSingleNode”和“ SelectNode”,但它們無法幫助我。 我想得到類似sql的結果-“從海報中選擇價格,數量= 200,庫存= 100”。
有什么建議么?
Xml到數據集:
string xmlDocString = Server.MapPath("MyXMLFile.xml");
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlDocString);
GridView1.DataSource = dataSet.Tables[0].DefaultView;
GridView1.DataBind();
使用XPath表達式和以下XML庫 :
int quantity = 200;
int stock = 100;
int newPrice = 55;
XElement root = XElement.Load(file);
XElement poster = root.XPathElement("//poster[quantity={0} and stock={1}]",
quantity, stock);
poster.Set("price", newPrice, false); // false for set child ELEMENT value
您可以使用LINQ to XML 。 它將使您擁有“像sql這樣的代碼”
這是在LINQPad中工作的代碼示例
void Main()
{
var xml = @"<posters>
<poster>
<quantity>100</quantity>
<stock>100</stock>
<price>88</price>
</poster>
<poster>
<quantity>100</quantity>
<stock>150</stock>
<price>95</price>
</poster>
<poster>
<quantity>200</quantity>
<stock>100</stock>
<price>95</price>
</poster>
<poster>
<quantity>200</quantity>
<stock>150</stock>
<price>100</price>
</poster>
</posters>";
var doc = XDocument.Parse(xml);
var value = (from x in doc.Descendants("poster")
where x.Element("stock").Value == "100"
&& x.Element("quantity").Value == "200"
select x.Element("price")).FirstOrDefault();
if (value != null)
value.SetValue("1000");
value.Dump();
doc.Dump();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.