【问题标题】:Regex to replace " with " only if it's not in another "正则表达式仅当它不在另一个时才将“替换为”
【发布时间】:2015-06-14 07:08:18
【问题描述】:

我正在将an encoded XML document 转换为其原始格式

string myXml = oldXml.Replace("&lt;", "<").Replace("&amp;", "&")
                                                   .Replace("&gt;", ">")
                                                   .Replace("&quot;", "\"")
                                                   .Replace("&apos;", "'");

它工作正常。但是,如果 &amp;quot; 在另一个 &amp;quot; 中,我想排除它。

例子:

原始 XML

//Note the title value
<v:shape id="_x0000_i1025" title="a&quot; title &quot;b"> </v:shape>

编码的 XML

&lt;v:shape id=&quot;_x0000_i1025&quot; title=&quot;a&quot; title &quot;b&quot;&gt; &lt;/v:shape&gt;

替换后恢复的 XML

//Note the title value
<v:shape id="_x0000_i1025" title="a" title "b"> </v:shape>

正如您所见,内部 &amp;quot; 不应转换为 "。那么我怎样才能用正则表达式进行替换,这样它就不会替换内部&amp;quot;

谢谢

【问题讨论】:

  • 从什么编码开始?如果可以的话,我会从源头上解决问题。 (如果它已将 &amp;amp; 编码为 &amp;amp; 会很好 - 事实上它没有这样做表明编码部分通常被严重破坏......)
  • @JonSkeet .Net 在我输入an xml in another xml attribute时会自动执行此操作
  • 我希望它能够正确地做到这一点。请提供一个简短但完整的原因示例。
  • 添加到@JonSkeet,编码后的 XML 应该是这样的:title=&amp;quot;a&amp;amp;quot; title(如果是这样,你的解码器就可以工作,尽管我会使用官方实现..)
  • @AlexJolig 例如HttpUtility.HtmlDecode()

标签: c# regex xml


【解决方案1】:

原来我不需要恢复编码的XML

由于nodElement.SetAttribute("myXmlAttribute", myXml);首先对原始Xml进行编码,当我读取属性值并将其分配给字符串时,C#将自动恢复原始Xml。

string content = theNode.Attributes["myXmlAttribute"].Value;

我不需要做任何替换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    相关资源
    最近更新 更多