修改XML文件中的内联节点值

时间:2016-09-15 12:44:40

标签: c# xml xml-parsing

我有以下XML文件。我想仅修改此XML文件中的Detail值,例如Genre,Title,Writer,ISBN。最后,应使用c#。

将文件与修改后的更改一起保存
<Book>
 <LibraryCode>LIB-0001</LibraryCode>

 <BookDetail>
    <Detail  Name="Genre" Value="fiction" />
    <Detail  Name="Title" Value="Book of thrones" />
    <Detail  Name="Writer" Value="King of Thrones" />
    <Detail  Name="ISBN" Value="108y387527" />
 </BookDetail> 
</Book>

请为此建议一个最佳解决方案。

2 个答案:

答案 0 :(得分:0)

您可以将xml文件读取为字符串,使用System.Xml对其进行处理,而不是再次保存。像这样:

   StringBuilder sb = new StringBuilder();
   using (StreamReader sr = new StreamReader("YourFile.xml")) 
   {
       String line;
       // Read and display lines from the file until the end of 
       // the file is reached.
       while ((line = sr.ReadLine()) != null) 
       {
           sb.AppendLine(line);
       }
    }
    string xmlString = sb.ToString();

    var doc = new XmlDocument();
    doc.Load(new StringReader(xmlString));

    XmlNodeList nodes = doc.GetElementsByTagName("Detail");
    foreach (XmlElement no in nodes)
    {
         XmlAttribute attr = doc.CreateAttribute("ISBN");
         attr.InnerText = "12345";
         no.Attributes.Append(attr);
    }

    using (StreamWriter writer = new StreamWriter("YourFile.xml", false))
    {
        writer.WriteLine(doc.ToString());
    }

答案 1 :(得分:0)

我发现以下代码工作正常并解决了我的问题。

XmlDocument doc = new XmlDocument();
doc.Load(FilePath);
XmlNodeList aNodes = doc.SelectNodes("/Book/BookDetail/Detail");
foreach (XmlNode aNode in aNodes)
{
  XmlAttribute NameAttribute = aNode.Attributes["Name"];
  XmlAttribute ValueAttribute = aNode.Attributes["Value"];

  if (NameAttribute != null)
  {
    string currentValue = NameAttribute.Value;
    if (currentValue == "ISBN")
     {
        ValueAttribute.Value = ISBN_value;
     }
     //Likewise we can change values of all the inline nodes in XML
  }
}