如何使用LINQ to XML获取XDocument的直接节点值?
嘿,我来帮你搞定用LINQ to XML提取目标XML里节点值的事儿!针对你给出的XML结构,我会分步骤给出具体的实现代码,清晰易懂。
第一步:加载XML文档
首先你需要把XML内容加载到XDocument对象里,不管是从字符串还是本地文件都可以:
从字符串加载
string xmlContent = @"<?xml version=""1.0""?> <response version=""1.0""> <respcode>200</respcode> <respmessage>Success</respmessage> <datetime>Thu, 18 Jan 2018 06:20:25 +0000</datetime> <location> <site_code>COH</site_code> <phone>781-383-0180</phone> <fax>781-383-9093</fax> <standardized_operation_hours> <Monday>07:30-17:00</Monday> <Tuesday>07:30-17:00</Tuesday> <Wednesday>07:30-17:00</Wednesday> <Thursday>07:30-17:00</Thursday> <Friday>07:30-17:00</Friday> <Saturday>Closed</Saturday> <Sunday>Closed</Sunday> </standardized_operation_hours> </location> </response>"; XDocument doc = XDocument.Parse(xmlContent);
从本地文件加载
如果XML是存放在文件里,直接用Load方法:
XDocument doc = XDocument.Load(@"C:\your\file\path\response.xml");
第二步:提取根节点下的直接子节点值
你要的<response>的直接子节点(比如respcode、respmessage、datetime)可以通过Root.Element()直接获取:
// 安全获取节点值,用?.避免节点不存在时抛出空引用异常 string respcode = doc.Root.Element("respcode")?.Value; string respmessage = doc.Root.Element("respmessage")?.Value; string datetime = doc.Root.Element("datetime")?.Value; // 输出结果示例 Console.WriteLine($"响应码: {respcode}"); Console.WriteLine($"响应消息: {respmessage}"); Console.WriteLine($"时间: {datetime}");
第三步:提取嵌套节点的值
对于<location>这类嵌套节点,先获取到对应的XElement对象,再提取它的子节点值:
// 获取<location>节点 XElement locationNode = doc.Root.Element("location"); if (locationNode != null) { string siteCode = locationNode.Element("site_code")?.Value; string phone = locationNode.Element("phone")?.Value; string fax = locationNode.Element("fax")?.Value; Console.WriteLine($"\n站点编码: {siteCode}"); Console.WriteLine($"联系电话: {phone}"); Console.WriteLine($"传真: {fax}"); // 提取营业时间节点 XElement hoursNode = locationNode.Element("standardized_operation_hours"); if (hoursNode != null) { Console.WriteLine("\n营业时间:"); // 遍历所有营业时间子节点 foreach (XElement dayNode in hoursNode.Elements()) { Console.WriteLine($"{dayNode.Name}: {dayNode.Value}"); } } }
关键说明
Element("节点名"):用于获取当前节点下第一个匹配名称的直接子节点;如果节点不存在,返回null。?.Value:C#的空条件运算符,确保当节点为null时不会抛出NullReferenceException,而是返回null。Elements():用于获取当前节点下的所有直接子节点,适合像营业时间这种多个同层级节点的场景。
内容的提问来源于stack exchange,提问作者Santosh Jami
相关产品推荐
相关产品推荐

