使用c#我已经将XML文件读入XML文档,并使用XPath在XMLNodeList代码列表中获取XMLNode列表。我想创建一个单独的List BlankCodes,它引用代码列表中符合条件的任何XmlNodes。
因此,我创建感兴趣的XmlNode列表的当前代码如下所示。
XmlDocument xDoc = new XmlDocument();
xDoc.Load("C:\\Test.XML");
List<int> blankCodes = new List<int>();
XmlNodeList codeList = xDoc.SelectNodes("codelist\\Code");
foreach( XmlNode aNode in codeList)
{
if(aNode.Value == "")
{
blankCodes.Add( (int)aNode.Attributes("Index")
}
}
然后,我将遍历blankCodes列表中的整数,再次在codeList中找到相应的节点,并修改节点中的另一个值。
是否可以在codeList中为相应的XmlNodes创建一个指针列表?然后,而不是必须通过xPath在codeList中找到XmlNodes或循环我可以直接引用XmlNode? p>
如果您能指导需要澄清的内容,我非常乐意尝试澄清。
非常感谢bommelding。
------下面的工作答案的演示代码-----------------
using System;
using System.Collections.Generic;
namespace TestReferences
{
/// <summary>
/// Basic Class to with index and value
/// </summary>
class aVal
{
public int Index { get; set; }
public int Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
//Create two lists of class to simulate XML node
List<aVal> originalList = new List<aVal>(); //Proper list as if read from XML
List<aVal> blankList = new List<aVal>(); //List of Blank Codes
//Loop to create 20 instances of class
for(int i = 1; i <= 20; i++)
{
//Create class
aVal temp = new aVal();
temp.Index = i; //Index
temp.Value = i * 2; //Easily Identifiable Value
originalList.Add(temp); //Add to original list
if( i == 4 || i==12 || i == 18) //Simulate Blank Codes
{
blankList.Add(originalList[originalList.IndexOf(temp)]); //Add the instance to blank list so we get a reference,
//I presume that I have to add the one in the list not the temporary instance used to populate the original list
}
}
//Write the original list to the console
//Expected output "Index 1 : Val 2"
Console.WriteLine("******* Original List ***************");
foreach( aVal te in originalList)
{
Console.WriteLine("Index {0} : Val {1}", te.Index, te.Value);
}
//Write the blank list to the console.
Console.WriteLine("******* Blank List ***************");
foreach (aVal te in blankList)
{
Console.WriteLine("Index {0} : Val {1}", te.Index, te.Value);
}
Console.WriteLine("*****************");
Console.WriteLine("Modifying Blanks");
Console.WriteLine("*****************");
//Set each instance.value to -99 referenced by the blanklist
foreach (aVal te in blankList)
{
te.Value = -99;
}
//Check the output, 4,12,18 should have value -99
Console.WriteLine("******* Original List after blanks modified ***************");
foreach (aVal te in originalList)
{
Console.WriteLine("Index {0} : Val {1}", te.Index, te.Value);
}
Console.ReadLine();
}
}
}
答案 0 :(得分:3)
是的,因为XmlNodes是普通的C#对象。您始终使用(通过)参考。
创建实例的副本需要做更多的工作,尤其是对于XmlDocument系列。
List<XmlNode> blankCodes = new List<XmlNode>();
if(aNode.Value == "")
{
blankCodes.Add(aNode);
}