C#/.Net - 快速解析XML的方法 / XML -> Json

3

我是新手,对XML不太熟悉,之前只接触过Json:( 我有一个XML文件,看起来像这样:

<AdapterCards>
    <cards type="MCS">
        <card>
            <id>id1</id>
            <description>desc1</description>
            <mccode>code1</mccode>
        </card>
        <card>
            <id>id2</id>
            <description>desc2</description>
            <mccode>code2</mccode>
        </card>
    </cards>
    <cards type="MCM">
        <card>
            <id>id3</id>
            <description>desc3</description>
            <mccode>code3</mccode>
        </card>
        <card>
            <id>id4</id>
            <description>desc4</description>
            <mccode>code4</mccode>
        </card>
    </cards>
    <cards type="F"/>
    <cards type="B"/>
</AdapterCards>

我希望将其解析为一个JSON字符串,应该像这样:
{[{'type': 'mcs', 'id': 'id1', 'description': 'desc1', 'mccode': 'code1'},
  {'type': 'mcs', 'id': 'id2', 'description': 'desc2', 'mccode': 'code2'},
  {'type': 'mcm', 'id': 'id3', 'description': 'desc3', 'mccode': 'code3'},
  {'type': 'mcm', 'id': 'id4', 'description': 'desc4', 'mccode': 'code4'}
]}

我的问题是我从未涉及过 XML(是的,我很惭愧)。 你能否给我一些关于如何快速解析XML的线索呢?(我已经将它上传到服务器上了,并且它是一个流。)我搜索了一些XML转换成JSON的工具,但是找不到适合我的,因为我需要一个“特殊”格式。

谢谢你们的答复!我正在使用C#。


你说的"快"是指执行速度吗?你有大量的数据或者XML->C#->JSON是个选项吗?你所说的"特殊格式"在哪里?是写起来很快吗?一个原始的XML读取器(以文本流作为输出)是我能想到的最快的方式,但它也是最不可重用的;带有自定义JSON序列化程序的LINQ to XML非常简单易行,但对于大量的数据性能并不好。最后,为什么不使用XSLT呢?如果数据量不大的话,这是最直接和灵活的解决方案。 - Adriano Repetti
@Adriano。XML不是很大,最多400或500行。我知道,我的问题在于序列化器,但为了能够序列化,我必须知道如何解析XML。我想使用LINQ to XML,因为我已经用过LINQ to SQL,但我还不知道要使用哪些方法以及如何做到这一点(如果我读了一些关于它的东西,我会自己做的,但我需要更快的速度,这就是为什么我要寻求一些线索的原因)。是的,XML转Json是我的唯一选择,因为客户端和服务器之间的通信只基于Json。我所谓的“特殊格式”是指Json字符串的结构。谢谢:) - darkdante
虽然不是很高效,但文件相当小:可以查看 XSD(http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=vs.100).aspx)。它将生成用于读取提供的 XML 文件的 C# 类。然后只需编写自己的 JSON _序列化器_(或使用内置的),即可完成。 - Adriano Repetti
4个回答

2
我最近自己为同样的事情编写了一个定制解决方案。我使用XSLT完成了这个任务,使用 XslCompiledTransform 类来运行XML输入并输出JSON。
这需要一些工作,但应该可以帮助您了解基础知识(它是从我所做的工作中复制粘贴出来的,稍加修改就可以满足您的需求)。

AdapterCards.XML

<AdapterCards>
    <cards type="MCS">
        <card>
            <id>id1</id>
            <description>desc1</description>
            <mccode>code1</mccode>
        </card>
        <card>
            <id>id2</id>
            <description>desc2</description>
            <mccode>code2</mccode>
        </card>
    </cards>
    <cards type="MCM">
        <card>
            <id>id3</id>
            <description>desc3</description>
            <mccode>code3</mccode>
        </card>
        <card>
            <id>id4</id>
            <description>desc4</description>
            <mccode>code4</mccode>
        </card>
    </cards>
    <cards type="F"/>
    <cards type="B"/>
</AdapterCards>

AdapterCards.XSL

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="no" omit-xml-declaration="yes" method="text" encoding="UTF-8" media-type="text/x-json" />

<xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />

    <!-- Main template for escaping strings; used by above template and for object-properties 
       Responsibilities: placed quotes around string, and chain up to next filter, escape-bs-string -->
    <xsl:template name="escape-string">
        <xsl:param name="s"/>
        <xsl:text>"</xsl:text>
        <xsl:call-template name="escape-bs-string">
            <xsl:with-param name="s" select="$s"/>
        </xsl:call-template>
        <xsl:text>"</xsl:text>
    </xsl:template>

    <!-- Escape the backslash (\) before everything else. -->
    <xsl:template name="escape-bs-string">
        <xsl:param name="s"/>
        <xsl:choose>
            <xsl:when test="contains($s,'\')">
                <xsl:call-template name="escape-quot-string">
                    <xsl:with-param name="s" select="concat(substring-before($s,'\'),'\\')"/>
                </xsl:call-template>
                <xsl:call-template name="escape-bs-string">
                    <xsl:with-param name="s" select="substring-after($s,'\')"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:call-template name="escape-quot-string">
                    <xsl:with-param name="s" select="$s"/>
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <!-- Escape the double quote ("). -->
    <xsl:template name="escape-quot-string">
        <xsl:param name="s"/>
        <xsl:choose>
            <xsl:when test="contains($s,'&quot;')">
                <xsl:call-template name="encode-string">
                    <xsl:with-param name="s" select="concat(substring-before($s,'&quot;'),'\&quot;')"/>
                </xsl:call-template>
                <xsl:call-template name="escape-quot-string">
                    <xsl:with-param name="s" select="substring-after($s,'&quot;')"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:call-template name="encode-string">
                    <xsl:with-param name="s" select="$s"/>
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <!-- Replace tab, line feed and/or carriage return by its matching escape code. Can't escape backslash
       or double quote here, because they don't replace characters (&#x0; becomes \t), but they prefix 
       characters (\ becomes \\). Besides, backslash should be seperate anyway, because it should be 
       processed first. This function can't do that. -->
    <xsl:template name="encode-string">
        <xsl:param name="s"/>
        <xsl:choose>
            <!-- tab -->
            <xsl:when test="contains($s,'&#x9;')">
                <xsl:call-template name="encode-string">
                    <xsl:with-param name="s" select="concat(substring-before($s,'&#x9;'),'\t',substring-after($s,'&#x9;'))"/>
                </xsl:call-template>
            </xsl:when>
            <!-- line feed -->
            <xsl:when test="contains($s,'&#xA;')">
                <xsl:call-template name="encode-string">
                    <xsl:with-param name="s" select="concat(substring-before($s,'&#xA;'),'\n',substring-after($s,'&#xA;'))"/>
                </xsl:call-template>
            </xsl:when>
            <!-- carriage return -->
            <xsl:when test="contains($s,'&#xD;')">
                <xsl:call-template name="encode-string">
                    <xsl:with-param name="s" select="concat(substring-before($s,'&#xD;'),'\r',substring-after($s,'&#xD;'))"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$s"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>


    <xsl:template match="card">
        <xsl:text>{</xsl:text>

        <xsl:text>"type":</xsl:text>
        <xsl:call-template name="escape-string">
            <xsl:with-param name="s" select="translate(../@type, $uppercase, $smallcase)"/>
        </xsl:call-template>

        <xsl:text>,"id":</xsl:text>
        <xsl:call-template name="escape-string">
            <xsl:with-param name="s" select="id"/>
        </xsl:call-template>

        <xsl:text>,"description":</xsl:text>
        <xsl:call-template name="escape-string">
            <xsl:with-param name="s" select="description"/>
        </xsl:call-template>

        <xsl:text>,"mccode":</xsl:text>
        <xsl:call-template name="escape-string">
            <xsl:with-param name="s" select="mccode"/>
        </xsl:call-template>

        <xsl:if test="following::card">},</xsl:if>
        <xsl:if test="not(following::card)">}</xsl:if>
    </xsl:template>


    <xsl:template match="/AdapterCards">
        <xsl:text>{[</xsl:text>

        <xsl:apply-templates select="cards/card" />

        <xsl:text>]}</xsl:text>
  </xsl:template>
</xsl:stylesheet>

C# (读作C Sharp)
// Load XML document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("AdapterCards.XML");

// Transform the XML into JSON
XslCompiledTransform transformer = new XslCompiledTransform();
using (var xslStylesheetFile = File.Open("AdapterCards.XSL", FileMode.Open))
{
    using (var xmlReader = new XmlTextReader(xslStylesheetFile))
    {
        transformer.Load(xmlReader);
    }
}
var sourceNavigator = xmlDoc.CreateNavigator();
using (MemoryStream ms = new MemoryStream())
{
    transformer.Transform(sourceNavigator, null, ms);
    ms.Position = 0;
    using (var sr = new StreamReader(ms))
    {
        return sr.ReadToEnd(); // <-- this is your JSON
    }
}

我在Notepad++中执行了上述XSL,并得到了以下结果:
{[{"type":"mcs","id":"id1","description":"desc1","mccode":"code1"},
{"type":"mcs","id":"id2","description":"desc2","mccode":"code2"},
{"type":"mcm","id":"id3","description":"desc3","mccode":"code3"},
{"type":"mcm","id":"id4","description":"desc4","mccode":"code4"}]}

如下所示,逗号应该放在需要的地方,但它几乎完成了!
更新了XSL和输出,现在逗号放在了正确的位置。接下来要解决的问题是"type"的大小写。我认为你可能需要使用XSL 2.0才能访问xpath function fn:lower-case()编辑3:已完成 - 现在将大小写转换为小写通过这个答案的帮助
参考资料:

0

这里有另一种简单的方法可以使用Cinchoo ETL,一个开源库,将XML转换为JSON文件。

using (var r = new ChoXmlReader("*** Xml file path ***")
       .WithXPath("//cards")
       )
{
    using (var w = new ChoJSONWriter("*** Json file path ***")
          )
        w.Write(r.SelectMany(r1 => ((dynamic[])r1.cards??new dynamic[]{}).Select(c => new { r1.type, c.id, c.description, c.mccode })));
}

示例代码片段:https://dotnetfiddle.net/Yzcaiw


0
使用JsonConvert类,该类包含用于此特定目的的辅助方法:
// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

文档在这里:使用 Json.NET 在 JSON 和 XML 之间进行转换


我已经尝试过了,但似乎在Jayrock.Json.Conversion中我没有SerializeXmlNode方法。 - darkdante
jayrock.json.conversion 库不是用于转换目的,请使用这里的库,其中也有示例 http://james.newtonking.com/projects/json/help/ 您可以从 http://json.codeplex.com/ 下载它。 - Meherzad

-3
XDocument xDoc = XDocument.Load(queryURL);                               
var x1 = from el in xDoc.Root.Descendants("results").Descendants("div").Descendants("div").Descendants("span").Attributes("class")
where el.Value == "pr"
  select el.Parent.Value;                
   stockFeed.Price = Decimal.Parse(x1.First().ToString());

LINQ是提取数据的最佳方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接