我有以下XML:
<Loop Name="MasterData">
<Loop Name="SlaveData">
<Segment Name="AAA">
<Node1>hello</Node1>
<Node2>john</Node2>
<Node3>hi</Node3>
<Node4>marry</Node4>
</Segment>
<Segment Name="BBB">
<Node1>00</Node1>
<Node2> </Node2>
<Node3>00</Node3>
<Node4> </Node4>
</Segment>
</Loop>
</Loop>我必须读取每个节点的值,即Node1、Node2、Node3、Node4,它们位于其属性为Name = "AAA"的分段节点下。我该怎么做呢。我指的是来自stackoverflow的以下链接,但这对我不起作用。
How to read attribute value from XmlNode in C#?
我需要这样的输出
假设我有四个刺变量strNode1, strNode2, strNode3, strNode4。我希望将值存储在上述四个变量中,如下所示
strNode1 = "hello"
strNode2 = "john"
strNode3 = "hi"
strNode4 = "marry"发布于 2013-04-23 12:59:40
我为我的问题找到了一个简单的解决方案
XmlNodeList xnList = doc.SelectNodes("/Loop/Loop/Segment[@Name='AAA']");
foreach (XmlNode xn in xnList)
{
if (xn.HasChildNodes)
{
foreach (XmlNode item in xn.ChildNodes)
{
Console.WriteLine(item.InnerText);
}
}
}发布于 2013-04-22 20:36:00
您可以使用XmlDocument将其作为对象加载,然后使用XPath查询所需的特定节点。您的xpath查询(我现在无法对其进行测试)可能如下所示。
XmlNodeList xNodes = xmlDocument.SelectNodes("//Segment[@Name = 'AAA']");发布于 2013-04-22 20:30:53
我建议使用XDocument (基于父节点的NB特定过滤等被省略):
var document = XDocument.Load(path);
var nodes = document.Descendents().Where(e => e.Name.LocalName.StartsWith("Node"));包含父元素过滤的更新
var nodes = document.Descendents()
.Where(e => e.Atrributes().Any(a => a.Name.localName == "Name" && a.Value == "AAA"))
.SelectMany(e => e.Descendents().Where(e => e.Name.LocalName.StartsWith("Node"));
var values = nodes.Select(n => n.Value).ToList(); // This will be a list containing "hello", "john, "hi", "marry"https://stackoverflow.com/questions/16147142
复制相似问题