gpt4 book ai didi

C# LINQ 和 XML 获取子节点

转载 作者:数据小太阳 更新时间:2023-10-29 02:34:27 26 4
gpt4 key购买 nike

获取节点值时出现问题。不确定为什么以下代码无法这样做。

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type='text/xsl' href='STIG_unclass.xsl'?>
<Benchmark xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cpe="http://cpe.mitre.org/language/2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" id="Windows_7_STIG" xml:lang="en" xsi:schemaLocation="http://checklists.nist.gov/xccdf/1.1 http://nvd.nist.gov/schema/xccdf-1.1.4.xsd http://cpe.mitre.org/dictionary/2.0 http://cpe.mitre.org/files/cpe-dictionary_2.1.xsd" xmlns="http://checklists.nist.gov/xccdf/1.1">
<status date="2015-06-16">accepted</status>
<title>Windows 7 Security Technical Implementation Guide</title>
<description>
The Windows 7 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. The requirements were developed from DoD consensus, as well as the Windows 7 Security Guide and security templates published by Microsoft Corporation. Comments or proposed revisions to this document should be sent via e-mail to the following address: disa.stig_spt@mail.mil.
</description>
<notice id="terms-of-use" xml:lang="en">Developed_by_DISA_for_the_DoD</notice>
<reference href="http://iase.disa.mil">
<dc:publisher>DISA, Field Security Operations</dc:publisher>
<dc:source>STIG.DOD.MIL</dc:source>
</reference>
<plain-text id="release-info">Release: 20 Benchmark Date: 24 Jul 2015</plain-text>
</Benchmark>

示例 XML 文件。

下面是我的代码。

String Title = LoadedXML.Element("Benchmark").Attribute("id").Value;
var XMLData = LoadedXML.Element("Benchmark").Elements("plain-text")
.Single(release => release.Attribute("id").Value == "release-info").Value;

有没有办法可以同时获取多个节点值?喜欢一次获得标题和发行值(value)而不是分别获得一个吗?

最佳答案

您的代码失败是因为您的 XML 包含 Namespace 并且您无法直接访问您的节点。如果您想确认这一点,只需查询 LoadedXML.Elements() 并检查调试器中的值,您可以清楚地看到那里的命名空间:-

enter image description here

因此,您需要声明命名空间并使用它:-

XNamespace ns = "http://checklists.nist.gov/xccdf/1.1";

如果您希望同时获取两个值,您可以将其投影为匿名类型,如下所示:-

var result = LoadedXML.Root.Elements(ns + "plain-text")
.Where(x => (string)x.Attribute("id") == "release-info")
.Select(x => new
{
Title = (string)x.Document.Root.Attribute("id"),
XMLData = x.Value
}).FirstOrDefault();

此查询给出以下输出:-

enter image description here

关于C# LINQ 和 XML 获取子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32492852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com