假设我使用以下XML字符串调用XElement.Parse():
var xml = XElement.Parse(@"
<?xml version="1.0" encoding="UTF-8"?>
<AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Owner>
<ID>7c75442509c41100b6a413b88b523bd6f46554cdbee5b6cbe27bc08cb3f6a865</ID>
<DisplayName>me</DisplayName>
</Owner>
<AccessControlList>
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">
...
");
当查询元素时,我被迫使用完全限定的元素名称,因为该XML文档的根目录中包含xmlns
属性。这需要繁琐的XName实例创建:
var AWS_XMLNS = "http://s3.amazonaws.com/doc/2006-03-01/";
var ownerElement = xml.Element(XName.Get("AccessControlPolicy", AWS_XMLNS)).Element(XName.Get("Owner", AWS_XMLNS));
当我真正想要的只是,
var ownerElement = xml.Element("AccessControlPolicy").Element("Owner");
有没有办法让LINQ to XML 假设一个特定的命名空间,所以我不必继续指定它?