gpt4 book ai didi

C# XML --> 如何获取属于该attributes元素的属性值和xpath

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:58 24 4
gpt4 key购买 nike

我正在寻找一种遍历 XML 文件并获取文本和 xpath 的一些属性的方法。但我不知道该怎么做。我知道如何从我想要的属性中获取所有文本,但问题是我看不到它所在的 xpath。有人能帮我吗?代码 =

       // XML settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreWhitespace = true;
settings.IgnoreComments = true;

// Loop through the XML to get all text from the right attributes
using (XmlReader reader = XmlReader.Create(sourceFilepathTb.Text, settings))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.HasAttributes)
{
if (reader.GetAttribute("Caption") != null)
{
MessageBox.Show(reader.GetAttribute("Caption"));
}
}
}
}
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<Test Description="Test XML" VersionFormat="123" ProtectedContentText="(Test test)">
<Testapp>
<TestappA>
<A Id="0" Caption="Test 0" />
<A Id="1" Caption="Test 1" />
<A Id="2" Caption="Test 2" />
<A Id="3" Caption="Test 3">
<AA>
<B Id="4" Caption="Test 4" />
</AA>
</A>
</TestappA>
<AA>
<Reason Id="5" Caption="Test 5" />
<Reason Id="6" Caption="Test 6" />
<Reason Id="7" Caption="Test 7" />
</AA>
</Testapp>
</Test>

最佳答案

恕我直言,LINQ to XML 更简单:

var document = XDocument.Load(fileName);

var captions = document.Descendants()
.Select(arg => arg.Attribute("Caption"))
.Where(arg => arg != null)
.Select(arg => arg.Value)
.ToList();

[更新]

为每个具有 Caption 属性的元素查找 XPath:

var captions = document.Descendants()
.Select(arg =>
new
{
CaptionAttribute = arg.Attribute("Caption"),
XPath = GetXPath(arg)
})
.Where(arg => arg.CaptionAttribute != null)
.Select(arg => new { Caption = arg.CaptionAttribute.Value, arg.XPath })
.ToList();

private static string GetXPath(XElement el)
{
if (el.Parent == null)
return "/" + el.Name.LocalName;

var name = GetXPath(el.Parent) + "/" + el.Name.LocalName;

if (el.Parent.Elements(el.Name).Count() != 1)
return string.Format(@"{0}[{1}]", name, (el.ElementsBeforeSelf(el.Name).Count() + 1));
return name;
}

关于C# XML --> 如何获取属于该attributes元素的属性值和xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6160879/

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