【问题标题】:how read unstructured xml in c# [closed]如何在 C# 中读取非结构化 xml [关闭]
【发布时间】:2014-08-17 15:33:39
【问题描述】:

我想阅读非结构化的 XML。子元素的数量可能会增加或减少。在 C# 中读取这种类型的 XML 的最佳方法是什么。示例 XML 如下所示

<?xml version="1.0" encoding="UTF-8"?>
<entities>
    <entity>
        <type>Organization</type>
        <relevance>0.918192</relevance>
        <sentiment>
            <type>neutral</type>
        </sentiment>
        <count>1</count>
        <text>Wheelers Hill Secondary College Deb Ball</text>
    </entity>
    <entity>
        <type>Organization</type>
        <relevance>0.621802</relevance>
        <sentiment>
            <type>positive</type>
            <score>0.789945</score>
        </sentiment>
        <count>1</count>
        <text>Greensborough College</text>
        <disambiguated>
            <name>Greensborough College</name>
            <subType>School</subType>
            <website>http://www.greensc.vic.edu.au/</website>
            <dbpedia>http://dbpedia.org/resource/Greensborough_College
            </dbpedia>
            <freebase>http://rdf.freebase.com/ns/m.0bp2jy</freebase>
        </disambiguated>
    </entity>
</entities>

【问题讨论】:

  • 我建议对 Linq to XML (XDocument) 进行一些研究。
  • 我进行了搜索,但这些都是读取结构化 XML 文件的所有方法,其中子元素的数量是恒定的。我想读取属性数量不恒定的 XML
  • 你的方案是什么?你想读取一些属性/元素,所有的,你想如何使用读取的数据?
  • 最佳方式是什么意思?你在看性能吗?
  • 我想读取所有 XML 元素。

标签: c# xml


【解决方案1】:

在 C# 中读取 XML 的最佳方法是使用 LINQ。您可以使用以下代码查询 XML 并获取所需的元素。

首先创建一个扩展方法来检查一个元素是否存在并返回它的值

public static string CheckAndGetElementValue(this XElement parent, string elementName, string defaultValue = null) 
{
    var el = parent.Element(elementName);
    if(el != null)
    {
         return el.Value;
    }
    else
    {
         return defaultValue;
    }
}

在获取元素值时使用扩展方法:

XDocument xDoc = XDocument.Load("filename");
var listitems = (from el in xDoc.Descendants("entities")
                where el.Element("entity").CheckAndGetElementValue("type") == "Organization"
                select el);

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 2016-03-10
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2012-08-22
    • 2022-11-24
    相关资源
    最近更新 更多