【问题标题】:Parsing XML in C# having json in attribute在 C# 中解析具有 json 属性的 XML
【发布时间】:2021-05-03 03:25:25
【问题描述】:

我有一个这样的 XML

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://sample.com/">

<ServerSideComponent 
    Name="SQL" 
    Id="100"    
    ComponentManifest=
        "{
        "id":"101",
        "componentType":"AnyType",
        "supportedHosts":["Win","Mac","Android","Linux"]
        }">
</ServerSideComponent>
</Elements>

我想从中解析 componentType 和 supportedHosts。 我怎么能在 C# 中做到这一点? 我尝试了 GetElementsByTag / GetAttributes,但无法做到。非常感谢任何帮助。

【问题讨论】:

  • 这不是有效的 XML,您在双引号中使用了双引号,因此会破坏解析。
  • 同意 XML 格式错误。上传到xmlvalidation.com会报错,10:11 Element type "ServerSideComponent" must be followed by either attribute specifications, "&gt;" or "/&gt;".
  • XML 格式错误,有两个问题。您有一个属性 ComponentManifest,它在双引号内有双引号。您还有一个额外的右尖括号,它在属性 ComponentType 的末尾不需要。

标签: c# xml parsing


【解决方案1】:

感谢您的 cmets。 在浏览了原始文件后,我将“替换为” 并且清单验证通过了

这是工作代码:

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(@"C:\Users\abc\file.xml");

            // Select nodes by TagName
            XmlNodeList nodeList = xmldoc.GetElementsByTagName("ServerSideComponent");
            foreach (XmlNode node in nodeList)
            {
                var Name = node.Attributes["ComponentManifest"].Value;
                dynamic stuff = JObject.Parse(Name);
                Console.WriteLine("supportedHosts: ");

                foreach (string host in stuff.supportedHosts)
                {
                    Console.WriteLine(host);

                }

                var componentType = stuff.componentType;
                Console.WriteLine("Component Type = " + componentType);
            }

【讨论】:

    猜你喜欢
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    相关资源
    最近更新 更多