使用C#将XML转换为JSON时摆脱@和#

时间:2018-07-12 09:43:01

标签: c# .net json xml

从XML转换为JSON时,我得到了@和#作为某些键的前缀。我不确定为什么在转换时会引入它们。如果尝试用替换方法替换它们,那么我也将丢失电子邮件字段。请帮助我使用string.replace做到这一点,这不是一个好习惯。

try
{
    string mongoEndpoint = "/?ssl=true&replicaSet=globaldb";

    MongoClient dbClient = new MongoClient(mongoEndpoint);


    string xml = System.IO.File.ReadAllText(@"C:\Users\HA304615\Downloads\WiproContrastCloud\injection_00005.xml");


    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    //xml to json
    string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(message, Newtonsoft.Json.Formatting.Indented);

    //Remove extra attributes from keys(not good`

    json = json.Replace("@", "");
    json = json.Replace("#", "");

    //Get Database  
    IMongoDatabase db = dbClient.GetDatabase("<Bayer_Database_Name>");

    //Get Collection
    var patientCol = db.GetCollection<BsonDocument>("<Collection_Name>");

    BsonDocument document = BsonDocument.Parse(json);
    patientCol.InsertOneAsync(document);
}
catch (Exception e)
{
    Console.WriteLine(e);
}

输出JSON:

{
  "?xml": {
    "@version": "1.0",
    "@encoding": "utf-8"
  },
  "ContrastDoseReport": {
    "@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
    "@xsi:schemaLocation": "MEDRAD_Injection_Report.XSD",
    "@xmlns": "http://www.medrad.com/ContrastDoseReport",
    "Patient": {
      "@id": "--",
      "Name": null,
      "Age": null,
      "Gender": "UNKNOWN",
      "DateOfBirth": null,
      "Height": {
        "@units": "cm",
        "#text": "0"
      },
      "Weight": {
        "@units": "kg",
        "#text": "0"
      }
    },
    /* ... */
  }
}

输入XML:

<?xml version="1.0" encoding="UTF-8"?>
<ContrastDoseReport xmlns="http://www.medrad.com/ContrastDoseReport" xsi:schemaLocation="MEDRAD_Injection_Report.XSD" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Patient id="--">
        <Name/>
        <Age/>
        <Gender>UNKNOWN</Gender>
        <DateOfBirth/>
        <Height units="cm">0</Height>
        <Weight units="kg">0</Weight>
    </Patient>
    <!-- ... -->
</ContrastDoseReport>

0 个答案:

没有答案