Best way to read, modify, and write XML

前端 未结 8 1918
灰色年华
灰色年华 2021-02-05 10:39

My plan is to read in an XML document using my C# program, search for particular entries which I\'d like to change, and then write out the modified document. However, I\'ve bec

8条回答
  •  深忆病人
    2021-02-05 11:18

    My favorite tool for this kind of thing is HtmlAgilityPack. I use it to parse complex HTML documents into LINQ-queryable collections. It is an extremely useful tool for querying and parsing HTML (which is often not valid XML).

    For your problem, the code would look like:

    var htmlDoc = HtmlAgilityPack.LoadDocument(stringOfHtml);
    var images = htmlDoc.DocumentNode.SelectNodes("//img[id=lookforthis]");
    
    if(images != null)
    {
      foreach (HtmlNode node in images)  
      {  
          node.Attributes.Append("alt", "added an alt to lookforthis images.");  
      }  
    }
    
    htmlDoc.Save('output.html');
    

提交回复
热议问题