删除所有未包含在 XML 大括号中的文本

Remove all text not wrapped in XML braces

我想从 XML 文档中删除所有无效文本。我认为任何未包含在 <> XML 括号中的文本都是无效的,并希望在翻译之前去除这些文本。

由此postRegular expression to remove text outside the tags in a string - it explains how to match XML brackets together. However on my example it doesn't clean up the text outside of the XML as can be seen in this example. https://regex101.com/r/6iUyia/1

我认为在我最初的研究中,S/O 上没有人问过这个具体的例子。

目前在我的代码中,我将此 XML 作为一个字符串,然后再根据它编写 XDocument。所以我可能有字符串、正则表达式和 XDocument 方法可用来帮助删除它,这些文档中可能还存在不止一位无效的 XML。此外,我不希望使用 XSLT 来删除这些值。

我曾尝试但未能构成的一个非常基本的想法是将字符串作为 char 数组进行迭代,如果它在“>”和“<”之外,则尝试将其删除但决定必须是实现这一目标的更好方法(因此是问题)

这是输入示例,嵌套 A 和嵌套 B 之间显示的文本无效

 <ASchema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdt="http://www.w3.org/2005/xpath-datatypes" xmlns:fn="http://www.w3.org/2005/xpath-functions">
   <A>
         <nested-A>valid text</nested-A>
         Remove text not inside valid xml braces
         <nested-B>more valid text here</nested-B>
   </A>
</ASchema>

我希望输出的格式如下所示。

 <ASchema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdt="http://www.w3.org/2005/xpath-datatypes" xmlns:fn="http://www.w3.org/2005/xpath-functions">
   <A>
         <nested-A>valid text</nested-A>
         <nested-B>more valid text here</nested-B>
   </A>
</ASchema>

您可以执行以下操作。请注意我只做了非常有限的测试,如果在某些情况下它失败了请告诉我。

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
var json = JsonConvert.SerializeXmlNode(doc);

string result = JToken.Parse(json).RemoveFields().ToString(Newtonsoft.Json.Formatting.None);
var xml = (XmlDocument)JsonConvert.DeserializeXmlNode(result);

其中 RemoveFields 定义为

public static class Extensions
{
public static JToken RemoveFields(this JToken token)
{
    JContainer container = token as JContainer;
    if (container == null) return token;

    List<JToken> removeList = new List<JToken>();
    foreach (JToken el in container.Children())
    {
        JProperty p = el as JProperty;
        if (p != null && p.Name.StartsWith("#"))
        {
            removeList.Add(el);
        }
        el.RemoveFields();
    }

    foreach (JToken el in removeList)
        el.Remove();

    return token;
}
}

输出

<ASchema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xdt="http://www.w3.org/2005/xpath-datatypes" xmlns:fn="http://www.w3.org/2005/xpath-functions">
   <A>
      <nested-A>valid text</nested-A>
      <nested-B>more valid text here</nested-B>
   </A>
</ASchema>

请注意我在上面的代码中使用了 Json.net