从 XML 文件中检索特定数据
本文关键字:数据 检索 XML 文件 | 更新日期: 2023-09-27 18:33:12
Using LINQ to XML.
我有一个XML文件,看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<TileMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Title>title</Title>
<Abstract>Some clever text about this.</Abstract>
<SRS>OSGEO:41001</SRS>
<Profile>global-mercator or something</Profile>
</TileMap>
通过使用这一小段代码,我可以毫无问题地从中检索<Title>
:
string xmlString = AppDomain.CurrentDomain.BaseDirectory + @"Capabilities'" + name + ".xml";
string xmlText = File.ReadAllText(xmlString);
byte[] buffer = Encoding.UTF8.GetBytes(xmlText);
XElement element = XElement.Load(xmlString);
IEnumerable<XElement> title =
from el in element.Elements("Title")
select el;
foreach (XElement el in title)
{
var elementValue = el.Value;
}
但是,这不是很灵活,因为假设我有一个如下所示的 XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<RootObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Services>
<TileMapService>
<Title>title</Title>
<href>http://localhost/root</href>
</TileMapService>
</Services>
</RootObject>
它找不到<Title>
但它找到了<Services>
(我猜),但由于它不被称为"标题",它只是忽略它。我在使用 XML 方面不是很强。我将如何制作一个查看XML并获取"标题"的方法,或者您将如何实现它?
您当前只查看根元素的子元素。
相反,如果要查找所有子体,请使用 Descendants
。
此外,使用 from x in y select x
的查询表达式是没有意义的(或者更确切地说,在某些情况下有一个非常有限的点,但不是这里)。所以只需使用:
var titles = element.Descendants("Title");
就我个人而言,我实际上会在这里使用XDocument
而不是XElement
- 毕竟你得到了一个完整的文档,完整的XML声明,而不仅仅是一个元素。
将 LINQ 查询更改为:
IEnumerable<XElement> title =
from el in element.Descendants("Title")
select el;
Elements
仅返回直接子节点,Descendants
返回所有后代节点。
后代将选择所有"标题"元素,无论级别如何。请使用 xpath 正确定位元素
using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using System.IO;
public class Program
{
public static void Main()
{
string xmlFile = AppDomain.CurrentDomain.BaseDirectory + @"Capabilities'" + name + ".xml";
XElement xml=XElement.Load(xmlFile);
IEnumerable<XElement> titleElements = xml.XPathSelectElements("//Services/TileMapService/Title");
}
}