c# XElement加载获取元素值

本文关键字:元素 获取 加载 XElement | 更新日期: 2023-09-27 17:54:29

我有以下XML,但努力获得DisplayName文本,它一直说它是一个空值:

<?xml version="1.0" encoding="utf-8"?>
<Package Test="Value">
<Identity Name="Reserved" Publisher="CN=Reserved" Version="0.0.0.0" />
<Properties>
    <DisplayName>Application Name</DisplayName>
    <PublisherDisplayName>Reserved</PublisherDisplayName>
    <Description>Reserved</Description>
    <Logo>Reserved.jpeg</Logo>
</Properties>
</Package>

我使用了下面的

XElement Manifest = XElement.Load(@"c:'temp'file.xml");
var ins = Manifest.Attribute("Test").Value.ToString();
var PackageName = Manifest.Element("Properties").Attribute("DisplayName").Value; // doesn't work

如何获得DisplayName文本?

在Powershell中非常容易,但我很难用c#

做同样的事情。
[xml]$manifest = gc "C:'temp'file.xml"
$manifest.Package.Test
$DisplayName = $manifest.Package.Properties.DisplayName

c# XElement加载获取元素值

var manifest = XElement.Load(@"C:'temp'log'foo.txt");
var packageName = manifest
    .Element("Properties")
    .Elements()
    .First(x => x.Name == "DisplayName")
    .Value;