Ben
Ben

Reputation: 1032

Read an XML node in namespace using Linq

How do I work out what the namespace declaration is for the Extension node?

I want to return all of the child nodes under: GPO->User->ExtensionData->Extension

<?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">
  <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>

This is my attempt:

Dim NS As XNamespace = "http://www.microsoft.com/GroupPolicy/Settings/Scripts"
Dim UserPolCount = XDoc.Descendants(NS + "Extension").First()

I get the following error: Sequence contains no elements

Also, the XML sample I have provided is only a small snippet, the ExtensionData->Extension nodes can be nested in different areas, so I was hoping to find the way of specifying the full path.

Thanks

Upvotes: 0

Views: 522

Answers (2)

DaveShaw
DaveShaw

Reputation: 52798

The Extension Element is still under the root namespace of:

http://www.microsoft.com/GroupPolicy/Settings

Elements under Extension are under the Scripts namespace:

http://www.microsoft.com/GroupPolicy/Settings/Scripts

So you need:

Dim NS As XNamespace = "http://www.microsoft.com/GroupPolicy/Settings/" 
Dim NS1 As XNamespace = "http://www.microsoft.com/GroupPolicy/Settings/Scipts" 
Dim UserPolCount = XDoc.Descendants(NS + "Extension").First() 
Dim ScriptNode = UserPolCount.Elements(NS1 + "Script")

EDIT From the comments:

Dim extension = 
    XDoc
    .Root
    .Element(NS + "User")
    .Element(NS + "ExtensionData")
    .Element(NS + "Extension");

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

You are using the wrong namespace. You need to use http://www.microsoft.com/GroupPolicy/Settings as the namespace.
The reason is that only the children of Extension are in the Scripts namespace. You can easily see this: The children are all prefixed with q1, the Extension tag itself not. Therefore it is defined in the default namespace, defined by the attribute xmlns="http://www.microsoft.com/GroupPolicy/Settings" on the root tag GPO.

Upvotes: 1

Related Questions