使用Linq读取XML节点值 [英] Read an XML node value using Linq

查看:81
本文介绍了使用Linq读取XML节点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当简单的要求.

I have what should be a fairly simple requirement.

我想在VS2010项目中使用LINQ to XML来获取以下节点值:

I want to use LINQ to XML in a VS2010 project to get the following node values:

GPO->名称

GPO-> LinksTo-> SOMName

GPO->LinksTo->SOMName

GPO-> LinksTo-> SOMPath

GPO->LinksTo->SOMPath

然后: 如果存在GPO-> User-> ExtensionDataCount节点,我想返回所有子节点的计数

Then: If GPO->User->ExtensionDataCount node exists, I want to return count of all child nodes

类似: 如果存在GPO-> Computer-> ExtensionData,则返回所有子节点的计数

Likewise: If GPO->Computer->ExtensionData exists, return count of all child nodes

这是XML,熟悉组策略导出的人以前会看到以下内容:

here is the XML, those of you familiar with Group Policy exports will have seen this before:

<?xml version="1.0" encoding="utf-16"?>
<GPO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.microsoft.com/GroupPolicy/Settings">
  <Identifier>
    <Domain xmlns="http://www.microsoft.com/GroupPolicy/Types">our.domain.fqdn</Domain>
  </Identifier>
  <Name>The Name I want to get</Name>
  <Computer>
    <VersionDirectory>1</VersionDirectory>
    <VersionSysvol>1</VersionSysvol>
    <Enabled>true</Enabled>
  </Computer>
  <User>
    <VersionDirectory>4</VersionDirectory>
    <VersionSysvol>4</VersionSysvol>
    <Enabled>true</Enabled>
    <ExtensionData>
      <Extension xmlns:q1="http://www.microsoft.com/GroupPolicy/Settings/Scripts" xsi:type="q1:Scripts">
        <q1:Script>
          <q1:Command>Logon.cmd</q1:Command>
          <q1:Type>Logon</q1:Type>
          <q1:Order>0</q1:Order>
          <q1:RunOrder>PSNotConfigured</q1:RunOrder>
        </q1:Script>
      </Extension>
      <Name>Scripts</Name>
    </ExtensionData>
  </User>
  <LinksTo>
    <SOMName>an interesting data value</SOMName>
    <SOMPath>some data value</SOMPath>
    <Enabled>true</Enabled>
    <NoOverride>false</NoOverride>
  </LinksTo>
</GPO>

我已将XML文件加载到XDocument中,然后尝试使用以下方法提取Name值:

I have loaded the XML file into an XDocument, then tried to pull the Name value with:

XDoc.Elements("Name").FirstOrDefault.Value
XDoc.Descendants("Name").First().Value

但是我遇到了错误:对象引用未设置为对象的实例,然后:序列不包含任何元素.

But I'm getting errors: Object reference not set to an instance of an object and then: Sequence contains no elements.

我猜我可能路径错误,但是我认为后代不需要确切的路径.

I'm guessing I might have the path wrong, but I thought Descendants didn't require an exact path..

我要去哪里错了?

推荐答案

您必须使用声明的名称空间:

You have to use the declared namespace:

XNamespace ns = "http://www.microsoft.com/GroupPolicy/Settings";
var firstName = xdoc.Descendants(ns + "Name").First().Value;

这篇关于使用Linq读取XML节点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆