为包含带或不带 CDATA 标签的数据的内容实现 IXmlSerialized
我正在尝试找出一种解析 xml 标签的方法,其中内容通过 CDATA 标签传入以用于某些输入,但不是全部。
例如,以下是我收到的包含 CDATA 标签的数据的示例内容。但还有一些其他场景会省略 CDATA 标签。
<Data><![CDATA[ <h1>CHAPTER 2<br/> EDUCATION</h1>
<P> Analysis paragraph </P> ]]></Data>
是否有一种优雅的方法来以某种方式检测到这一点,并实现可以解析两种类型的输入(有或没有 CDATA)的 ReadXml 方法?到目前为止,我的 ReadXml() 实现如下,但在省略 CDATA 标记时出现解析错误。
public void ReadXml(XmlReader reader)
{
bool isEmpty = reader.IsEmptyElement;
reader.ReadStartElement();
if (isEmpty)
{
_data = string.Empty;
}
else
{
switch (reader.MoveToContent())
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
_data = reader.ReadContentAsString();
break;
default:
_data = string.Empty;
break;
}
reader.ReadEndElement();
}
}
I am trying to figure out a way to parse an xml tag where content is passed in with CDATA tags for some input, but not for all.
For example, the following is sample content I would receive for data which contains CDATA tags. But there is some other scenarios where the CDATA tags are ommited.
<Data><![CDATA[ <h1>CHAPTER 2<br/> EDUCATION</h1>
<P> Analysis paragraph </P> ]]></Data>
Is there an elegant way to somehow detect that, and implement ReadXml method that can parse both types of input (with or without CDATA)? So far my ReadXml() implementation is as follows, but am getting errors parsing when CDATA tag is omitted.
public void ReadXml(XmlReader reader)
{
bool isEmpty = reader.IsEmptyElement;
reader.ReadStartElement();
if (isEmpty)
{
_data = string.Empty;
}
else
{
switch (reader.MoveToContent())
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
_data = reader.ReadContentAsString();
break;
default:
_data = string.Empty;
break;
}
reader.ReadEndElement();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下面的代码在以下示例上进行了测试:
我使用 XPathNavigator,因为它允许回溯。
The code below is tested on the following samples:
I use an XPathNavigator instead as it allows backtracking.