【问题标题】:modify inline node values in XML file修改 XML 文件中的内联节点值
【发布时间】:2016-09-15 12:44:39
【问题描述】:

我有以下 XML 文件。我只想修改此 XML 文件中的详细信息值,例如流派、标题、作家、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>

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

【问题讨论】:

    标签: c# xml xml-parsing


    【解决方案1】:

    您可以将 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());
        }
    

    【讨论】:

      【解决方案2】:

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

      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
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-28
        • 2015-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多