本文介绍了如何在没有数据时阻止XmlSerializer中的自闭关标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public string XmlSerializer(Object item) { StringBuilder builder = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; using (XmlWriter xmlWriter = XmlWriter.Create(builder, settings)) { XmlSerializer xmlSerializer = new XmlSerializer(item.GetType()); XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }); nameSpaces.Add("", ""); xmlSerializer.Serialize(xmlWriter, item, nameSpaces); } return builder.ToString(); }
O / P: -
O/P :-
<get_country_details_response> <country_id>10.0000</country_id> <country_name>10.0000</country_name> <currency_name /> <!-- Need to Avoid This Self Closing Tag --> </get_country_details_response>推荐答案
一个选项是使用正则表达式对输出进行一些后处理: 首先定义以下正则表达式以找到空标签: One option is to perform some post-processing of the output using regular expressions: First define the following Regex to find the empty tags: static Regex emptyElementRegex = new Regex(@"<(\w+)\s*/>");
然后处理您的输出以替换所有匹配的事件:
Then process your output to replace all matching occurrences:
var result = builder.ToString(); result = emptyElementRegex.Replace(result, @"<1>); 1>");
这应该转换所有没有属性的自动关闭标签。
This should transform ALL self-closing tags without attributes.
更多推荐
如何在没有数据时阻止XmlSerializer中的自闭关标签
发布评论