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

4

2 回答 2

4

Level2Root与元素在同一个命名空间中Level1(后代元素继承使用xmlns属性定义的命名空间,直到重新定义命名空间),因此您需要ns +在这两种情况下使用,即:

doc.Descendants(ns + "Level1").Elements(ns + "Level2"))
于 2013-09-08T21:23:29.233 回答
0

您可以按如下方式获取根的默认命名空间:

var ns = doc.Root.GetDefaultNamespace();
于 2013-09-09T06:27:47.470 回答