选择元素中的特定属性

本文关键字:属性 元素 选择 | 更新日期: 2023-09-27 18:12:41

我有一个xml数据库,其中有一些细节,但我有困难获得一个属性的值。我正在使用XDocument - linq to xml.

我数据库:

<?xml version="1.0" encoding="utf-8"?>
<Bundle xmlns="urn:uiosp-bundle-manifest-2.0" Name="ContactUsPlugin" SymbolicName="ContactUsPlugin" Version="1" InitializedState="Active">
  <Activator Type="ContactUsPlugin.Activator" Policy="Immediate" />
  <Runtime>
    <Assembly Path="bin'ContactUsPlugin.dll" Share="false" />
  </Runtime>
  <Functionality>
    <Controller>About</Controller>
    <View>Index</View>
  </Functionality>
  <Scripts>
    <Script version="1">
      <Location>E:'Git Projects'Kapsters'Plugins'ContactUsPlugin'Sql'Sql1.txt</Location>
    </Script>
    <Script version="2">
      <Location>E:'Git Projects'Kapsters'Plugins'ContactUsPlugin'Sql'Sql1.txt</Location>
    </Script>
  </Scripts>
</Bundle>

我正在尝试从元素程序集获取路径属性。

What i tried:

 var assemblyLocation =
            ManifestDocument.Element(ns + "Bundle").Element("Runtime").Element("Assembly").Attribute("Path").Value;
     var assemblyLocation =
            ManifestDocument.Root.Descendants("Runtime").Select(x => x.Element("Assembly").Attribute("Path").Value).First();
    var assemblyLocation =
           (from db in ManifestDocument.Root.Descendants("Runtime") select db.Element("Assembly").Attribute("Path").Value).First();

选择元素中的特定属性

您需要在Descendants()方法中指定名称空间,否则它只会返回null:

XNamespace ns = XNamespace.Get("urn:uiosp-bundle-manifest-2.0");
XDocument ManifestDocument = XDocument.Load(@"myxml.xml");
string path;
var assemplyElement = ManifestDocument.Descendants(ns + "Assembly").FirstOrDefault();
if (assemplyElement != null)
{
    path = (string)assemplyElement.Attribute("Path");
}