【问题标题】:Ignore namespace attributes while serializing xml data to json将 xml 数据序列化为 json 时忽略命名空间属性
【发布时间】:2021-01-23 14:19:48
【问题描述】:

我正在尝试使用JsonSerializer() 将 xml 直接序列化为 json,但命名空间属性正在作为最终 json 中的字段添加。关于如何删除它的任何建议?我尝试使用JsonConvert.Serialize(),但序列化的 json 中缺少一些子节点。

【问题讨论】:

    标签: json .net xml vb.net jsonserializer


    【解决方案1】:

    解决您的问题的方法可能是首先将您的对象反序列化为字典。这样您就可以在转换之间添加一些逻辑。

    查看以下示例:

                var xml = @"<?xml version='1.0' standalone='no'?>
                <root>
                  <person id='1'>
                    <name>Alan</name>
                    <url>http://www.google.com</url>
                  </person>
                  <person id='2'>
                    <name>Louis</name>
                    <url>http://www.yahoo.com</url>
                  </person>
                </root>";
    
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
    
                var childNodeList = doc.DocumentElement.ChildNodes;
    
                for (int i = 0; i < childNodeList.Count; i++)
                {
                    var nodes = childNodeList.Item(i).ChildNodes;
    
                    var dict = new Dictionary<string, object>();
    
                    foreach (XmlNode node in nodes)
                    {
                        var serializedNode = JsonConvert.SerializeXmlNode(node);
    
                        var prop = JsonConvert.DeserializeObject<IDictionary<string, object>>(serializedNode).FirstOrDefault();
    
                        dict.Add(prop.Key, prop.Value ?? " ");
                    }
    
                    Console.WriteLine($"item {i}");
                    Console.WriteLine(string.Join("\r\n", dict.Select(e => $"{e.Key}: {e.Value}")));
                }
    
    

    输出:

         //item 0
         //name: Alan
         //url: http://www.google.com
         //item 1
         //name: Louis
         //url: http://www.yahoo.com
    

    【讨论】:

    • 感谢您的回复。我能够将 xml 序列化为 json。我关心的是命名空间。它们需要被移除。如果您查看您共享的文档,在转换规则中,您可以看到属性是使用@infront 转换的。我根本不需要它们。您还熟悉用空格替换空值的任何方法吗? Nullvaluehandling.ignore 不工作
    • @TimLeslie 我已经更新了我的答案。我希望这会对你有所帮助!
    猜你喜欢
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2018-10-19
    • 2016-05-26
    • 2013-08-17
    • 2019-01-26
    相关资源
    最近更新 更多