How to handle JSON to remove a period from field names?

As a continuation of this question, I cannot figure out how to remove the period from all my field names in the JSON input.

I convert the XML to JSON and create a BsonDocument to insert into the MongoDB database using the Newtonsoft library as follows:

XmlDocument doc = new XmlDocument();
doc.Load(filePath);

String jsonText = JsonConvert.SerializeXmlNode(doc);

BsonDocument = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(jsonText);

I cannot insert this because I will get an exception for serialization, because the element name contains a period. How can I process either a JSON string or a BsonDocument to modify them?

I successfully repeated my document recursively:

private void Print(BsonDocument document)
{
    foreach (BsonElement element in document)
    {
        Console.WriteLine(element.Name);

        if (element.Value.IsBsonDocument)
        {
            Print(element.Value.AsBsonDocument);
        }
        else if (element.Value.IsBsonArray)
        {
            var array = element.Value.AsBsonArray;
            foreach (BsonDocument doc in array)
            {
                Print(doc);
            }
        }
    }
}

However, BsonDocument.Name is not a field that I can set, only get. How can I update a BsonDocument or JSON string to remove invalid field names?

+4
1

XML/JSON, XML, JSON ElementNames? ANSWER?

XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.LoadXml(File.ReadAllText(@"{path}\xml.xml", Encoding.Default));

        XmlNodeList nodeList = xmlDoc.SelectNodes("//*['.' = substring(name(), string-length(name())- string-length('.') +1)]");

        foreach (XmlNode node in nodeList)
        {

            string newName = node.Name.Replace(".", "");
            // create new (renamed) Content node
            XmlNode newNode = xmlDoc.CreateElement(newName);

            newNode.InnerXml = node.InnerXml;

            // replace existing BatteryTest node with newly renamed Content node
            node.ParentNode.InsertBefore(newNode, node);
            node.ParentNode.RemoveChild(node);
        }

        xmlDoc.Save(@"{path}\xml.xml");
+2

Source: https://habr.com/ru/post/1621967/


All Articles