我正在将 JSON 文件从 jsonrpc 转换为 XML。
但是当字段未填写时,API 会给出带有
false
值的字段,例如街道2
{
"jsonrpc": "2.0",
"id": null,
"code": 200,
"result": [
{
"id": 32,
"name": "Somebody",
"street": "21 golfcountry",
"street2": false,
"city": "Amsterdam"
},
{
"id": 38,
"name": "Somebody else",
"street": "27 golfcountry",
"street2": "sub lane 21",
"city": "Amsterdam"
}
]
}
因此 XML 解析为
<street2>false</street2>
和
<street2>sub lane 21</street2>
我想在转换之前删除那些错误字段。 我怎样才能删除这些错误值
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
这是一个使用 XSLT 删除不需要的 XML 元素作为后处理步骤的解决方案。
它使用所谓的 Identity Transform XSLT 模式。
输入XML
<root>
<jsonrpc>2.0</jsonrpc>
<code>200</code>
<result>
<id>32</id>
<name>Somebody</name>
<street2>false</street2>
<city>Amsterdam</city>
</result>
<result>
<id>38</id>
<name>Somebody else</name>
<street2>sub lane 21</street2>
<city>Amsterdam</city>
</result>
</root>
XSLT 1.0
<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes"
encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!--Identity transform-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[text()='false']" />
</xsl:stylesheet>
输出XML
<root>
<jsonrpc>2.0</jsonrpc>
<code>200</code>
<result>
<id>32</id>
<name>Somebody</name>
<city>Amsterdam</city>
</result>
<result>
<id>38</id>
<name>Somebody else</name>
<street2>sub lane 21</street2>
<city>Amsterdam</city>
</result>
</root>
c#
void Main()
{
const string SOURCEXMLFILE = @"e:\Temp\input.xml";
const string XSLTFILE = @"e:\Temp\process.xslt";
const string OUTPUTXMLFILE = @"e:\temp\output.xml";
try
{
XsltArgumentList xslArg = new XsltArgumentList();
using (XmlReader src = XmlReader.Create(SOURCEXMLFILE))
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(XSLTFILE, new XsltSettings(true, true), new XmlUrlResolver());
XmlWriterSettings settings = xslt.OutputSettings.Clone();
settings.IndentChars = "\t";
// to remove BOM
settings.Encoding = new UTF8Encoding(false);
using (XmlWriter result = XmlWriter.Create(OUTPUTXMLFILE, settings))
{
xslt.Transform(src, xslArg, result, new XmlUrlResolver());
result.Close();
}
}
Console.WriteLine("File '{0}' has been generated.", OUTPUTXMLFILE);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}