我有一个如下所示的 XML 文件:
<Main>
<Element1 Property1="Hello" Property3="world">
<Element1.Property2>again</Element1.Property2>
<Element1.Property3>Dave</Element1.Property3>
</Element1>
<Element2 Property1="Hello" Property3="world">
<Element2.Property2>again</Element2.Property2>
<Element2.Property1>
<SpecialElementForSayingHi/>
</Element2.Property1>
</Element2>
</Main>
我需要使用 XPath 匹配以下元素 - 除非有一种方法可以使用模式禁止它们存在,但我不相信有:
<Element1.Property3>Dave</Element1.Property3>
...
<Element2.Property1>
<SpecialElementForSayingHi/>
</Element2.Property1>
具体来说,我需要匹配元素名称采用以下格式的所有元素:
ParentElementName.NameOfAttributeThatExistsOnTheParentElement
我在 .Net 中工作,不想为此使用外部库,所以如果这可以使用 XPath 1.0 实现,那将是理想的。如果效率更高,我愿意使用匹配重复属性而不是元素的系统。
编辑:实际上没有问题。我该怎么做?
最佳答案
我曾尝试使用 XPAth 1.0 来实现,但没有成功,或许可以使用 XPath 2 或 XQuery 来实现。 在 .NET 中,最好使用 LINQ:
var xml = @"
<Main>
<Element1 Property1=""Hello"" Property3=""world"">
<Element1.Property2>again</Element1.Property2>
<Element1.Property3>Dave</Element1.Property3>
</Element1>
<Element2 Property1=""Hello"" Property3=""world"">
<Element2.Property2>again</Element2.Property2>
<Element2.Property1>
<SpecialElementForSayingHi/>
</Element2.Property1>
</Element2>
</Main>";
var doc = XDocument.Load(new StringReader(xml));
var result = doc.Root.Descendants().
Where(x => x.Parent.Attributes().
Any(y => x.Name == x.Parent.Name + "." + y.Name)
);
如果你想得到字符串结果,你可以这样做
var result = doc.Root.Descendants().
Where(x => x.Parent.Attributes().
Any(y => x.Name == x.Parent.Name + "." + y.Name)
).Select(e => e.ToString()).Aggregate((current, next) => current + next);
关于.net - 当属性已声明为父级的属性时,使用 XPath 匹配名称格式为 ParentElement.Property 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13661851/