2

I can read an XML doc using LINQ when there is no namespace in the root but retrieve nothing when it is present.

The code is used to step through the document:

foreach (XElement element in doc.Descendants("Level1").Elements("Level2"))

I also tried to get the namespace

var ns = doc.Root.Name.Namespace
foreach (XElement element in doc.Descendants(ns + "Level1").Elements("Level2"))

The document is set out as

<?xml version="1.0" encoding="UTF-8"?>
<Root xmlns="xmlns://www.example.com/schema/root" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.11" xsi:type="FVDL">
<Level1>
<Level2>
etc

Can anyone point our where I am going wrong :)

Thanks

2 Answers 2

4

Level2 is in the same namespace as the Root and the Level1 elements (the descendant elements inherit namespaces defined with the xmlns attribute until the namespace is redefined) so you need to use ns + in both cases i.e.:

doc.Descendants(ns + "Level1").Elements(ns + "Level2"))
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant... I had wrongly assumed that once in the namespace at the root, then the child items would be picked up. Thank you
0

You can get the default namespace of the root as follows:

var ns = doc.Root.GetDefaultNamespace();

2 Comments

Nice comment, but that should not be posted as answer
Well, I think this is the answer of the point where user have tried to get the namespace of the given xml, that's why I have posted it as answer

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.