gpt4 book ai didi

c# - LinQ to XML 访问元素及其值

转载 作者:行者123 更新时间:2023-12-04 17:05:45 25 4
gpt4 key购买 nike

对不起,我的英语不好...

我尝试从我的示例 XML 代码中获取元素“Member”及其值的枚举。此代码由外部程序生成。我将此 xml 文件缩小为一个示例。


<?xml version="1.0" encoding="utf-8"?>
<Document>
<SW.Types.PlcStruct ID="0">
<AttributeList>
<Interface>
<Sections xmlns="http://www.siemens.com/automation/Openness/SW/Interface/v4">
<Section Name="None">
<Member Name="FirstMember" Datatype="Word"><AttributeList><BooleanAttribute Name="ExternalAccessible" SystemDefined="true">true</BooleanAttribute></AttributeList><Comment><MultiLanguageText Lang="de-DE">FirstMemberComment</MultiLanguageText></Comment></Member>
<Member Name="SecondMember" Datatype="Word"><AttributeList><BooleanAttribute Name="ExternalAccessible" SystemDefined="true">true</BooleanAttribute></AttributeList><Comment><MultiLanguageText Lang="de-DE">SecondMemberComment</MultiLanguageText></Comment></Member>
</Section>
</Sections>
</Interface>
</AttributeList>
</SW.Types.PlcStruct>
</Document>


我一直到“接口(interface)”元素,但除此之外我无法访问数据。
XElement xelement = XElement.Load(xmlPath);
IEnumerable<XElement> udtContent = xelement.Element("SW.Types.PlcStruct").Element("AttributeList").Element("Interface").Elements();

这是因为那个 xml 文件中的那个 xmlns 命名空间标记吗?
如果我现在调试 udtContent 我得到这个:
{<Sections xmlns="http://www.siemens.com/automation/Openness/SW/Interface/v4">
<Section Name="None">
<Member Name="FirstMember" Datatype="Word">
<AttributeList>
<BooleanAttribute Name="ExternalAccessible" SystemDefined="true">true</BooleanAttribute>
</AttributeList>
<Comment>
<MultiLanguageText Lang="de-DE">FirstMemberComment</MultiLanguageText>
</Comment>
</Member>
<Member Name="SecondMember" Datatype="Word">
<AttributeList>
<BooleanAttribute Name="ExternalAccessible" SystemDefined="true">true</BooleanAttribute>
</AttributeList>
<Comment>
<MultiLanguageText Lang="de-DE">SecondMemberComment</MultiLanguageText>
</Comment>
</Member>
</Section>
</Sections>}

希望你能给我一个提示如何获得“成员”元素的枚举......

最佳答案

命名空间是问题。你可以使用这样的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication2
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);

List<XElement> members = doc.Descendants().Where(x => x.Name.LocalName == "Member").ToList();
XNamespace ns = members.FirstOrDefault().GetDefaultNamespace();

foreach (XElement member in members)
{
foreach (XElement booleanAttribute in member.Descendants(ns + "BooleanAttribute"))
{
string name = (string)booleanAttribute.Attribute("Name");
}
}
}
}
}

关于c# - LinQ to XML 访问元素及其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62188004/

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