【发布时间】:2015-04-01 21:12:17
【问题描述】:
我有以下 xml;
<?xml version="1.0" encoding="utf-8" ?>
<XslMapper>
<type name="article" xsl="http://localhost:8080/Xsl-a.xslt">
<category name="1234" xsl="http://localhost:8080/Xsl-b.xslt"></category>
<category name="1234" xsl="http://localhost:8080/Xsl-b.xslt"></category>
</type>
<type name="slideshow" xsl="http://localhost:8080/Xsl-c.xslt" >
<category name="1234" xsl="http://localhost:8080/Xsl-b.xslt"></category>
</type>
</XslMapper>
用于解析的C#代码;
WebClient client = new WebClient();
StringBuilder builder = new StringBuilder();
string downloadString = client.DownloadString(XslMapperFileAddress);
XmlDocument xml = new XmlDocument();
xml.LoadXml(downloadString);
XmlWriter writer = XmlWriter.Create(builder, new XmlWriterSettings() { OmitXmlDeclaration = true });
xml.Save(writer);
string xmlString = builder.ToString();
xml.LoadXml(xmlString);
string jsonText = JsonConvert.SerializeXmlNode(xml, Formatting.Indented, true);
jsonText = Regex.Replace(jsonText, "(?<=\")(@)(?!.*\":\\s )", string.Empty, RegexOptions.IgnoreCase);
XslMapper xslMapper = JsonConvert.DeserializeObject<XslMapper>(jsonText);
return xslMapper.XmlMapperTypes;
当我使用 json.net 将此 xml 序列化为 json 时,我得到以下结果;
{
"type": [
{
"name": "article",
"xsl": "http://localhost:8080/Services/Xsl-a.xslt",
"category": [
{
"name": "1234",
"xsl": "http://localhost:8080/Services/Xsl-b.xslt"
},
{
"name": "1234",
"xsl": "http://localhost:8080/Services/Xsl-b.xslt"
}
]
},
{
"name": "slideshow",
"xsl": "http://localhost:8080/Services/Xsl-c.xslt",
"category": {
"name": "1234",
"xsl": "http://localhost:8080/Services/Xsl-b.xslt"
}
}
]
}
如您所见,第一类部分被解析为一个数组(我打算这样做),第二部分被转换为对象。这就是为什么我从 JSON.NET 收到错误
如何将第二部分解析为类似数组;
"category": [
{
"name": "1234",
"xsl": "http://localhost:8080/Services/Xsl-b.xslt"
}
]
},
【问题讨论】:
-
什么是 XslMapper 类?它是您创建的还是第三方库的一部分?