【问题标题】:How to change the value of node如何更改节点的值
【发布时间】:2015-04-06 16:11:27
【问题描述】:

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>

【问题讨论】:

  • 做一个简单的谷歌搜索 C# stackoverflow how to change a node value in xml file 互联网上的大量工作示例
  • 在 C# 中使用 XML 已在许多地方反复广泛地介绍过。像@MethodMan 推荐的粗略的谷歌搜索是一个很好的起点。请先尝试一下,当您对您编写的代码有更具体的问题时再回来。

标签: c# xml


【解决方案1】:

您可以像这样尝试使用 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

没有尝试编译,但应该足够接近。

【讨论】:

    【解决方案2】:

    这样处理你的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; 
            }
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 2013-02-02
      • 1970-01-01
      相关资源
      最近更新 更多