简体   繁体   中英

XML String with no parent node to JSON with C#

I have an XML string that does not contain a parent node. This XML is a representation of a json request for an API. It seems pointless, but it is done this way to make it easy for non programmers to read the file. In order to convert the XML to json, pretty much everything i have seen says to convert the string to an XMLDocument and then use the following to get the json.

string jsonText = JsonConvert.SerializeXmlNode(doc);

The problem i have here is that the xml is not really valid and because of this, it cannot be converted to an xml document. What i really want is to be able to do this.

string jsonText = JsonConvert.SerializeXmlNode(doc.InnerXml);

This doesnt work since innerXML is a string and not an object. I have been able to get it to work by creating a root element and then just using a sub string to cut the resulting string, but this seems pointless. There has to be a better way to do this without having to add xml only to have to remove it from the json afterwards. Is it possible to convert a piece of xml like the xml below into json like the example below.

<rootnode>
    <fielda>a</fielda>
    <fieldb>b</fieldb>
</rootnode>

Converts to

  {
    "fielda": "a",
    "fieldb": "b"
  }

有一个布尔值omitRootObject SerializeXmlNode omitRootObject

string jsonText = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);

JsonConvert.SerializeXmlNode has an overloaded method which you could use to ignore root.

string jsonText = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);

Third parameter is for omitting RootObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM