0

I have what should be a fairly simple requirement.

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

GPO->Name

GPO->LinksTo->SOMName

GPO->LinksTo->SOMPath

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

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

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>

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..

Where am I going wrong?

1 Answer 1

2

You have to use the declared namespace:

XNamespace ns = "http://www.microsoft.com/GroupPolicy/Settings";
var firstName = xdoc.Descendants(ns + "Name").First().Value;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Haven't come across XNamespace before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.