加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.net – 当属性已被声明为父元素的属性时,使用XPath匹配名称格式

发布时间:2020-12-16 23:06:48 所属栏目:百科 来源:网络整理
导读:我有一个类似如下的 XML文件: Main Element1 Property1="Hello" Property3="world" Element1.Property2again/Element1.Property2 Element1.Property3Dave/Element1.Property3 /Element1 Element2 Property1="Hello" Property3="world" Element2.Property2ag
我有一个类似如下的 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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读