避免< item type>在JSON中创建节点到C#中的XML转换器 [英] Avoid <item type> node from creating in JSON to XML converter in C#

查看:86
本文介绍了避免< item type>在JSON中创建节点到C#中的XML转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试使用以下C#代码将JSON转换为XML:

We are trying to convert JSON to XML with following C# code:

Object httpConn = Dts.Connections["HTTP"].AcquireConnection(null);
            HttpClientConnection myConnection = new HttpClientConnection(httpConn);
            myConnection.ServerURL = string.Format(("http://xxxx.com/jjjj"),"userid","password");
            byte[] webdata = myConnection.DownloadData();

            String result_data = Convert.ToBase64String(webdata);
            XmlDocument xd = new XmlDocument();
            XmlDictionaryReader xr = JsonReaderWriterFactory.CreateJsonReader(webdata, XmlDictionaryReaderQuotas.Max);

            xr.Read();
            xd.LoadXml(xr.ReadOuterXml());
            xd.Save("\\Server\\ZZZZ\\Downloads\\Data.xml"); 

示例json是:

[
{
        "id" : 21953,
        "mainReqIdentity" : "xxxx",
        "itemName" : "xxxx",
        "kanbanPhase" : "xxxx",
        "kanbanStatus" : "xxxx",
        "backlogItemType" : "xxxx",
        "identityDomain" : "xxxx",
        "fromDatetime" : "2016-08-05 17:52:34",
        "teams" : [],
        "releases" : [{
                "id" : 1229,
                "release_name" : "xxxx",
                "release_connection_type" : "xxxx"
            }
        ],
        "fpReleases" : [],
        "sources" : [{
                "sourceName" : "xxxx",
                "sourceRecordUrl" : "xxxx",
                "sourceRecordIdentity" : "xxxx"
            }
        ],
        "productNumbers" : [],
        "tags" : [],
        "productComponents" : [],
        "ranPlatforms" : [],
        "subReleases" : [],
        "requirementAreaId" : "xxxx",
        "requirementArea" : "xxxx",
        "toBeHandledAtxxxx" : "xxxx"
    }, {
        "id" : 22014,
        "mainReqIdentity" : "xxxx",
        "itemName" : "xxxx",
        "kanbanPhase" : "xxxx",
        "kanbanStatus" : "xxxx",
        "backlogItemType" : "xxxx",
        "identityDomain" : "xxxx",
        "fromDatetime" : "2016-08-05 17:52:34",
        "teams" : [],
        "releases" : [{
                "id" : "xxxx",
                "release_name" : "xxxx",
                "release_connection_type" : "xxxx"
            }
        ],
        "fpReleases" : [],
        "sources" : [{
                "sourceName" : "xxxx",
                "sourceRecordUrl" : "xxxx",
                "sourceRecordIdentity" : "xxxx"
            }
        ],
        "productNumbers" : [],
        "tags" : [],
        "productComponents" : [],
        "ranPlatforms" : [],
        "subReleases" : [],
        "requirementAreaId" : "xxxx",
        "requirementArea" : "xxxx",
        "f0Date" : "2015-10-01",
        "f1Date" : "2015-10-01",
        "f2Date" : "2016-02-01",
        "f4Date" : "2016-03-31",
        "fgDate" : "2016-04-29",
        "toBeHandledAtxxxx" : "xxxx"
    }
    ]

转换后的XML如下:

    <root type="array">
    <id type="number">21286</id>
    <mainReqIdentity type="string">xxxxxx</mainReqIdentity>
    <itemName type="string">xxxxxx</itemName>
    <kanbanPhase type="string">xxxxxx</kanbanPhase>
    <kanbanStatus type="string">xxxxxx</kanbanStatus>
    <kanbanNote type="string">xxxxxx</kanbanNote>
    <backlogItemType type="string">xxxxxx</backlogItemType>
    <identityDomain type="string">xxxxxx</identityDomain>
    <fromDatetime type="string">2016-08-23 17:01:52</fromDatetime>
    <teams type="array">
      <item type="object">
        <team_name type="string">xxxxxx</team_name>
        <preliminary type="boolean">xxxxxx</preliminary>
      </item>
    </teams>
    <releases type="array">
      <item type="object">
        <id type="number">xxxxxx</id>
        <release_name type="string">xxxxxx</release_name>
        <release_connection_type type="string">xxxxxx</release_connection_type>
      </item>
    </releases>
    <fpReleases type="array">
    </fpReleases>
    <sources type="array">
      <item type="object">
        <sourceName type="string">xxxxxx</sourceName>
        <sourceRecordUrl type="string">xxxxxx</sourceRecordUrl>
      </item>
    </sources>
    <productNumbers type="array">
    </productNumbers>
    <tags type="array">
    </tags>
    <productComponents type="array">
    </productComponents>
    <ranPlatforms type="array">
    </ranPlatforms>
    <subReleases type="array">
    </subReleases>
    <requirementAreaId type="number">xxxxxx</requirementAreaId>
    <requirementArea type="string">xxxxxx</requirementArea>
    <itemContact type="string">xxxxxx</itemContact>
    <toBeHandledAtxxx type="string">xxxxxx</toBeHandledAtxxx>
  </item>
    <item type="object">
    <id type="number">xxxxxx</id>
    <mainReqIdentity type="string">xxxxxx</mainReqIdentity>
    <itemName type="string">xxxxxx</itemName>
    <kanbanPhase type="string">xxxxxx</kanbanPhase>
    <kanbanStatus type="string">xxxxxx</kanbanStatus>
    <kanbanNote type="string">xxxxxx</kanbanNote>
    <backlogItemType type="string">xxxxxx</backlogItemType>
    <identityDomain type="string">xxxxxx</identityDomain>
    <fromDatetime type="string">2016-08-23 17:01:52</fromDatetime>
    <teams type="array">
      <item type="object">
        <team_name type="string">xxxxxx</team_name>
        <preliminary type="boolean">xxxxxx</preliminary>
      </item>
    </teams>
    <releases type="array">
      <item type="object">
        <id type="number">xxxxxx</id>
        <release_name type="string">xxxxxx</release_name>
        <release_connection_type type="string">xxxxxx</release_connection_type>
      </item>
    </releases>
    <fpReleases type="array">
    </fpReleases>
    <sources type="array">
      <item type="object">
        <sourceName type="string">xxxxxx</sourceName>
        <sourceRecordUrl type="string">xxxxxx</sourceRecordUrl>
      </item>
    </sources>
    <productNumbers type="array">
    </productNumbers>
    <tags type="array">
    </tags>
    <productComponents type="array">
    </productComponents>
    <ranPlatforms type="array">
    </ranPlatforms>
    <subReleases type="array">
    </subReleases>
    <requirementAreaId type="number">xxxxxx</requirementAreaId>
    <requirementArea type="string">xxxxxx</requirementArea>
    <oaResultReference type="string">xxxxxx</oaResultReference>
    <itemContact type="string">xxxxxx</itemContact>
    <f0Date type="string">2014-10-17</f0Date>
    <f1Date type="string">2015-01-16</f1Date>
    <f2Date type="string">2015-02-13</f2Date>
    <f4Date type="string">2015-06-12</f4Date>
    <faDate type="string">2015-06-12</faDate>
    <fgDate type="string">2015-06-12</fgDate>
    <toBeHandledAtxxx type="string">xxxxxx</toBeHandledAtxxx>
  </item>
 </root>

如果您在每个节点之前都观察到一个 项目类型 .我的问题是如何避免从C#类创建它们.

If you observer before every node a item type is created. My question is how to avoid creating them from the C# class.

推荐答案

JsonReaderWriterFactory使用的XML和JSON之间的对应关系在

The correspondence between XML and JSON used by JsonReaderWriterFactory is described in Mapping Between JSON and XML. In particular:

  • 由于XML没有数组原语的概念,因此JSON数组映射到XML的两个级别,其中内部元素的[本地名称]将为"item".

  • Since XML does not have the concept of an array primitive, a JSON array is mapped to two levels of XML where the inner element’s [local name] will be "item".

属性"type"被添加到每个元素.如文档中所述,此属性用于在映射的XML中保留JSON类型(字符串,数字,布尔值,对象,数组或null).

An attribute "type" is added to each element. As stated in the docs, This attribute is used to preserve the JSON type (string, number, boolean, object, array or null) in the mapped XML.

如果此映射不满足您的需求,则可以使用一些适当的API(例如

If this mapping does not meet your needs, you can customize the resulting XML using some appropriate API such as an XSLT transformation or a LINQ to XML modification before storing the XML.

例如, LINQ to XML ,该API取代了.net 3.5中的XmlDocument API,可以轻松修改内存中的XML.首先,将JSON加载到 XDocument 如下:

For instance, LINQ to XML, the API which superseded the XmlDocument API in .Net 3.5, allows for easy modification of XML in memory. First, load your JSON into an XDocument as follows:

XDocument xd;
using (var xr = JsonReaderWriterFactory.CreateJsonReader(webdata, XmlDictionaryReaderQuotas.Max))
{
    xd = XDocument.Load(xr);
}

现在,如果要从其外部容器元素中取消嵌套"数组项,则可以按以下步骤进行操作-除非是根元素.如果XML文档的根元素与JSON数组相对应,则其内容无法冒泡,因为这样做因此会违反每个XML文档必须具有完全是一个根元素的规则.话虽如此,以下应该起作用:

Now, if you would like to "un-nest" the array items from their outer container element, you can do it as follows - except in the case of the root element. If the root element of the XML document corresponds to a JSON array its items cannot be bubbled out because doing so would violate the rule that each XML document must have exactly one root element. That being said, the following should work:

foreach (var arrayElement in xd.Root.Descendants().Where(e => (string)e.Attribute("type") == "array").ToList())
{
    // Get all child nodes of the array container node.
    var nodes = arrayElement.Nodes().ToList();
    bool anyChildren = false;
    // Change names of child elements from <item> to the name of the container node, <releases> or whatever.
    foreach (var element in nodes.OfType<XElement>())
    {
        anyChildren = true;
        element.Name = arrayElement.Name;
    }
    if (anyChildren)
    {
        // Remove all its child nodes.
        nodes.Remove();
        // Add formerly child nodes right after the container node.
        arrayElement.AddAfterSelf(nodes);
        // Remove the container node itself.
        arrayElement.Remove();
    }
}

(对于嵌套的JSON数组,可能需要进一步自定义此代码.)

(This code may need to be customized further for nested JSON arrays.)

接下来,如果要删除"type"属性,则可以使用以下代码:

Next, if you wish to remove the "type" attributes, the following code can be used:

foreach (var element in xd.Descendants().Where(e => e.Attribute("type") != null))
    element.Attributes("type").Remove();

最后,要保存文件,请执行以下操作:

Finally, to save the document afterwards, do:

xd.Save("\\Server\\ZZZZ\\Downloads\\Data.xml");

链接这两个转换的结果是:

The result of chaining these two transformation is:

<root>
  <item>
    <id>21953</id>
    <mainReqIdentity>xxxx</mainReqIdentity>
    <itemName>xxxx</itemName>
    <kanbanPhase>xxxx</kanbanPhase>
    <kanbanStatus>xxxx</kanbanStatus>
    <backlogItemType>xxxx</backlogItemType>
    <identityDomain>xxxx</identityDomain>
    <fromDatetime>2016-08-05 17:52:34</fromDatetime>
    <teams></teams>
    <releases>
      <id>1229</id>
      <release_name>xxxx</release_name>
      <release_connection_type>xxxx</release_connection_type>
    </releases>
    <fpReleases></fpReleases>
    <sources>
      <sourceName>xxxx</sourceName>
      <sourceRecordUrl>xxxx</sourceRecordUrl>
      <sourceRecordIdentity>xxxx</sourceRecordIdentity>
    </sources>
    <productNumbers></productNumbers>
    <tags></tags>
    <productComponents></productComponents>
    <ranPlatforms></ranPlatforms>
    <subReleases></subReleases>
    <requirementAreaId>xxxx</requirementAreaId>
    <requirementArea>xxxx</requirementArea>
    <toBeHandledAtxxxx>xxxx</toBeHandledAtxxxx>
  </item>
  <item>
    <id>22014</id>
    <mainReqIdentity>xxxx</mainReqIdentity>
    <itemName>xxxx</itemName>
    <kanbanPhase>xxxx</kanbanPhase>
    <kanbanStatus>xxxx</kanbanStatus>
    <backlogItemType>xxxx</backlogItemType>
    <identityDomain>xxxx</identityDomain>
    <fromDatetime>2016-08-05 17:52:34</fromDatetime>
    <teams></teams>
    <releases>
      <id>xxxx</id>
      <release_name>xxxx</release_name>
      <release_connection_type>xxxx</release_connection_type>
    </releases>
    <fpReleases></fpReleases>
    <sources>
      <sourceName>xxxx</sourceName>
      <sourceRecordUrl>xxxx</sourceRecordUrl>
      <sourceRecordIdentity>xxxx</sourceRecordIdentity>
    </sources>
    <productNumbers></productNumbers>
    <tags></tags>
    <productComponents></productComponents>
    <ranPlatforms></ranPlatforms>
    <subReleases></subReleases>
    <requirementAreaId>xxxx</requirementAreaId>
    <requirementArea>xxxx</requirementArea>
    <f0Date>2015-10-01</f0Date>
    <f1Date>2015-10-01</f1Date>
    <f2Date>2016-02-01</f2Date>
    <f4Date>2016-03-31</f4Date>
    <fgDate>2016-04-29</fgDate>
    <toBeHandledAtxxxx>xxxx</toBeHandledAtxxxx>
  </item>
</root>

这篇关于避免&lt; item type&gt;在JSON中创建节点到C#中的XML转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆