【发布时间】:2021-08-22 12:32:58
【问题描述】:
我正在读取重复的 xml 节点并将值填充到对象中。我可以在调试模式下看到节点正在更改每个循环,但对象仍填充有来自第一个节点的值。
Stackoverflow 希望我添加更多文本,所以这里是:
填充 noteNodes 的调用工作正常,在检查时我可以看到所有三个节点都按预期填充。
在第一个 foreach 子句中,经过检查,我可以看到代码每次都使用正确的节点。
只有在分配到 Step 和 Octave 时,它才会恢复到第一个音符的值。
class Program
{
class Note
{
private int sequence;
private string step;
private string octave;
public string Step { get => step; set => step = value; }
public int Sequence { get => sequence; set => sequence = value; }
public string Octave { get => octave; set => octave = value; }
public override string ToString()
{
return $"[{sequence}] {step} {octave}";
}
}
static void Main(string[] args)
{
XmlDocument guitarTab = new XmlDocument();
List<Note> notes = new List<Note>();
try
{
guitarTab.Load(AppDomain.CurrentDomain.BaseDirectory + "\\Tab-example.xml");
XmlNodeList noteNodes = guitarTab.SelectNodes("//score-partwise/part/measure/note");
int sequence = 0;
foreach (XmlNode node in noteNodes)
{
Note note = new Note();
note.Sequence = sequence++;
note.Step = node.SelectSingleNode("//pitch/step").InnerText;
note.Octave = node.SelectSingleNode("//pitch/octave").InnerText;
notes.Add(note);
}
foreach (Note note in notes)
{
Console.WriteLine(note.ToString());
}
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<score-partwise>
<part id="P1">
<measure number="1">
<note>
<pitch>
<step>E</step>
<octave>3</octave>
</pitch>
</note>
<note>
<pitch>
<step>D</step>
<octave>5</octave>
</pitch>
</note>
<note>
<pitch>
<step>B</step>
<octave>7</octave>
</pitch>
</note>
</measure>
</part>
</score-partwise>
结果:
[0] E 3
[1] E 3
[2] E 3
【问题讨论】:
-
//pitch/step将选择文档中的第一个step节点。从中删除//,使其相对于node进行导航。 -
非常感谢。为什么不把它作为答案,这样我就可以选择它。