title: Removing invalid child nodes but keep its contents intact..?
body: <p>I have some xml files that look like <a href="https://codeshare.io/2pz4MX" rel="nofollow noreferrer">sample file</a></p>
  
  <p>I want to remove invalid <code>xref</code> nodes from it but keep the contents of those nodes as it is.</p>
  
  <p>The way to know whether a <code>xref</code> node is valid is to check its attribute <code>rid</code>'s value exactly matches any of the attributes <code>id</code> of any node present in the entire file, so the output file of the above sample should be something like <a href="https://codeshare.io/2KwR4o" rel="nofollow noreferrer">sample output file</a></p>
  
  <p>The code I've written thus far is below</p>
  
  <pre><code>XDocument doc=XDocument.Load(@"D:\sample\sample.xml",LoadOptions.None);
  
  
              var ids = from a in doc.Descendants()
                  where a.Attribute("id") !=null
                  select a.Attribute("id").Value;
              var xrefs=from x in doc.Descendants("xref")
                  where x.Attribute("rid")!=null
                  select x.Attribute("rid").Value;
              if (ids.Any() &amp;&amp; xrefs.Any())
              {
                  foreach(var xref in xrefs)
                  {
                      if (!ids.Contains(xref))
                      {
  
                          string content= File.ReadAllText(@"D:\sample\sample.xml");
                          string result=Regex.Replace(content,"&lt;xref ref-type=\"[^\"]+\" rid=\""+xref+"\"&gt;(.*?)&lt;/xref&gt;","$1");
                          File.WriteAllText(@"D:\sample\sample.xml",result);
                      }
  
                  }
                  Console.WriteLine("complete");
              }
              else
              {
                  Console.WriteLine("No value found");
              }
  
              Console.ReadLine();
  </code></pre>
  
  <p>The problem is when the values of <code>xref</code> contain characters like <code>., *, (</code>etc. which on a regex replace needs to be escaped properly or the replace can mess up the file.</p>
  
  <p>Does anyone have a better solution to the problem?</p>