我忘记了什么? 似乎我以前做过这个,没有任何问题。当我遍历 XmlNodeList 时,我想获取每个节点的值,但我似乎一遍又一遍地获取第一个节点。
string strXpathHL1Loop = "//*[local-name()='HLLoop1']";
XmlNodeList nodeList = xmlDoc856.SelectNodes(strXpathHL1Loop);
Console.WriteLine("Number HLLoop1 nodes=" + nodeList.Count);
int lineNum = 0;
int loopNum = 0;
foreach (XmlNode node in nodeList)
{
loopNum++;
Console.WriteLine("n-----LoopNum=" + loopNum);
Console.WriteLine(node.OuterXml);
string xpathHL01 = "//HL01";
XmlNode HL01Node = node.SelectSingleNode(xpathHL01);
Console.WriteLine("HL01Node.OuterXml=" + HL01Node.OuterXml);
Console.WriteLine("HL01=" + HL01Node.InnerText);
string xpathHl03 = "//HL03";
XmlNode Hl03Node = node.SelectSingleNode(xpathHl03);
Console.WriteLine("HL03Node.OuterXml=" + Hl03Node.OuterXml);
Console.WriteLine("HL03=" + Hl03Node.InnerText);
}
-----LoopNum=1
<ns0:HLLoop1 xmlns:ns0="http://schemas.microsoft.com/BizTalk/EDI/X12/2006"><ns0:
HL><HL01>1</HL01><HL02 /><HL03>S</HL03></ns0:HL><ns0:TD5><TD501>B</TD501><TD505>
UNSP_CG</TD505></ns0:TD5><ns0:DTM_2><DTM01>011</DTM01><DTM02>20190425</DTM02></n
s0:DTM_2></ns0:HLLoop1>
HL01Node.OuterXml=<HL01>1</HL01>
HL01=1
HL03Node.OuterXml=<HL03>S</HL03>
HL03=S
-----LoopNum=2
<ns0:HLLoop1 xmlns:ns0="http://schemas.microsoft.com/BizTalk/EDI/X12/2006"><ns0:
HL><HL01>2</HL01><HL02>1</HL02><HL03>O</HL03></ns0:HL><ns0:PRF><PRF01>287775</PR
F01></ns0:PRF></ns0:HLLoop1>
HL01Node.OuterXml=<HL01>1</HL01>
HL01=1
HL03Node.OuterXml=<HL03>S</HL03>
HL03=S
循环 2 的预期结果:
HL01=2
HL03Node.OuterXml=<HL03>O</HL03>
HL03=O
以下是要重现的最少数据:
<ns0:X12_00401_856 xmlns:ns0="http://schemas.microsoft.com/BizTalk/EDI/X12/2006">
<ns0:HLLoop1>
<ns0:HL>
<HL01>1</HL01>
<HL02/>
<HL03>S</HL03>
</ns0:HL>
</ns0:HLLoop1>
<ns0:HLLoop1>
<ns0:HL>
<HL01>2</HL01>
<HL02>1</HL02>
<HL03>O</HL03>
</ns0:HL>
</ns0:HLLoop1>
</ns0:X12_00401_856>
使用相对于node
上下文节点向下的路径,例如
string xpathHL01 = ".//HL01";
或
string xpathHL01 = "descendant::HL01";
您从 /
开始的尝试从上下文节点的根节点/文档节点开始搜索/选择,因此每次选择最终都会得到相同的节点。