LINQ to XML:查找具有特定属性的元素

本文关键字:属性 元素 to XML 查找 LINQ | 更新日期: 2023-09-27 18:19:13

为了简化问题陈述,我试图搜索并查看文件中是否存在某个元素。我的XML文件是AndroidManifest.xml文件,用于Android应用程序。具体来说,我正在搜索类型为"use -permission"的元素,元素名称为"android:name",值为"android.permission. internet"。很简单,对吧?

查询是,

IEnumerable<XElement> address =
    from el in _rootElement.Elements( "uses-permission" )
        where (string)el.Attribute( "android:name" ) == "android.permission.INTERNET"
        select el;

问题是"android:name"中的名称空间不能在查询中使用。那么我该如何进行这个查询呢?我在其他地方看到了一些抱怨和建议,但无法将它们合并到我的具体查询中。

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.app.myapp">
<uses-permission android:name="android.permission.INTERNET"/>
    <application android:allowBackup="true" android:icon="@drawable/app_icon" android:label="App">
        <activity android:configChanges="fontScale|keyboard|keyboardHidden" android:name="com.unity3d.player.UnityPlayerProxyActivity" android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

LINQ to XML:查找具有特定属性的元素

您可以使用XNamespace来表示名称空间前缀,并使用XNamespace +属性的本地名称来指向名称空间中的属性:

XNamespace ns = "http://schemas.android.com/apk/res/android";
IEnumerable<XElement> address =
            from el in doc.Root.Elements("uses-permission")
            where (string)el.Attribute(ns+"name") == "android.permission.INTERNET"
            select el;

在使用LINQ to XML方法时,需要使用XName对象来查找具有特定名称空间的对象。

简单地说,名称空间声明混淆了LINQ to XML数据结构中XElementXAttribute的真正XName

XName只是围绕{<namespace>}<object name>的构造

所以你应该在.Attribute()方法调用中寻找的不是"android:name"而是"{http://schemas.android.com/apk/res/android}name"