【发布时间】:2018-06-05 12:02:51
【问题描述】:
使用 c# 我已将 XML 文件读入 XML 文档,并使用 XPath 获取 XMLNodeList 代码列表中的 XMLNode 列表。我想创建一个单独的 List BlankCodes,它引用 codelist 中符合条件的任何 XmlNodes。
所以我当前创建感兴趣的 XmlNodes 列表的代码如下所示。
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 的指针列表?那么我可以直接引用XmlNode而不是通过xPath在codeList中查找XmlNodes或循环访问?
如果您可以指导需要澄清的内容,我非常乐意尝试并提供澄清。
非常感谢您的好评。
-----下面的工作答案演示代码-----
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();
}
}
}
【问题讨论】:
-
myList.Add(aNode) -
附注,但请确保您了解 XDocument 。使用该 API 可以轻松解决很多 XML 问题。
-
说实话。我从未见过在确认所选答案时编辑过任何问题,显示它的效果如何!!
-
但是这里
blankList.Add(originalList[originalList.IndexOf(temp)]);你确定你不能做得比这更好吗? -
我觉得如果有人给你一个部分答案,那么创建演示所花费的时间是值得的。至于添加对刚刚添加的项目的引用,如果您有更好的方法,请随时启发我。