我有一个来自未净化的 WebService 的“XML”响应。这意味着它包含非法字符、特殊字符、html标签和十六进制。
净化此响应的最佳方法是什么?
这是来自服务的 Xml 示例。
<root>
<response>
<type>E</type>
<code>CMNE_00034</code>
<source>CMNQ3030</source>
<message>some valid message here.</message>
<detail>Error details here
line 114: endif
line 115: edit
line 116: else
> line 117: call LP_ACCEPT()
line 118: return ($status)
line 119: endif
line 120: done<end of module> // invalid here
at CMNQ3030.EXEC line 117: call LP_ACCEPT()
at GPCSY_RUN line 5: activate INSTANCENAME."EXEC"( )
at CSYV1000.LOGON line 159: call GPCSY_RUN()
</detail>
</response>
</root>
我尝试了很多方法,从创建一个具有如下设置的 XmlReader
开始。
public XDocument CreateXmlDocument(string content)
{
using (var reader = XmlReader.Create(new StringReader(content), CreateXmlReaderSettings()))
{
return XDocument.Load(reader);
}
}
private static XmlReaderSettings CreateXmlReaderSettings()
{
return new XmlReaderSettings { CheckCharacters = false };
}
在实际读取之前从 XmlDocument 更改为 XDocument 并使用 Encoding.UTF8.GetBytes
。
最佳答案
不太可能 XMLReader
, XDocument
等等。.NET 中的基础设施会很乐意被要求读取和解析格式错误的 XML。
我建议在将 XML 加载到 XML 对象之前对其进行预处理。
在上述情况下,Web 服务似乎在 <detail>...</detail>
中返回一条错误消息。元素应该像这样包装在 CDATA 中:
<root>
<response>
<type>E</type>
<code>CMNE_00034</code>
<source>CMNQ3030</source>
<message>some valid message here.</message>
<detail><![CDATA[
Error details here
line 114: endif
line 115: edit
line 116: else
> line 117: call LP_ACCEPT()
line 118: return ($status)
line 119: endif
line 120: done<end of module> // invalid here
at CMNQ3030.EXEC line 117: call LP_ACCEPT()
at GPCSY_RUN line 5: activate INSTANCENAME."EXEC"( )
at CSYV1000.LOGON line 159: call GPCSY_RUN()
]]>
</detail>
</response>
</root>
您应该能够很快地组合一个解析器来查找、提取和包装 <detail>
末尾之间的文本。标签和 </detail>
的开头<[CDATA[
内的标签和]]>
标签。
当然,您的服务的 XML 中可能还有其他字段也包含字符串数据或格式错误的字符等,您可能需要查找并替换这些字符,例如使用正则表达式等。
一旦更正,您应该可以轻松地将干净的 XML 加载到 XMLDocuments/XDocuments 等中。
HTH。
关于c# - 来自 WebService 的未经净化的 XML,如何净化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29092593/