Delete an inner node but not the value in xml with XDocument library in C# .NET

…衆ロ難τιáo~ 提交于 2019-12-20 03:09:02

问题


I have the following XML file:

<?xml version="1.0" encoding="utf-8"?>
<html>
  <body>
    <p><span class="screenitems">Add</span></p>
  </body>
</html>

I Want it to delete <span> node but the Add to exist, so it looks as follows at the end:

<?xml version="1.0" encoding="utf-8"?>
<html>
  <body>
    <p>Add</p>
  </body>
</html>

Is there a good/simple way to do this?


回答1:


Use ReplaceWith, e.g.

XDocument doc = XDocument.Load("file.xml");
XElement span = doc.Descendants("p").First().Elements("span").FirstOrDefault(s => (string)s.Attribute("class") == "screenitems");
if (span != null) 
{
  span.ReplaceWith(span.Nodes());
}



回答2:


Remark: Your XML looks like HTML-Code. HTML is not always a valid XML (see the BR-Tag: <br>). That might cause exceptions - so you either should be very sure that your HTML is a valid XML (then you can use XDocument) or you should use Regex.Replace()

Regex spanRegex = new Regex(@"<span[^>]*>([\s\S]*?)</span[^>]*>");
spanRegex.Replace(input, match => { return match.Groups[1].ToString(); });

(see http://regexr.com/3cjuq)



来源:https://stackoverflow.com/questions/34874027/delete-an-inner-node-but-not-the-value-in-xml-with-xdocument-library-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!