我使用类Node创建我的TreeViewItems。在示例中,节点在源代码中指定。但是,如果要从具有以下内容的文本文件导入节点,我该怎么做呢
有什么想法吗?
我尝试了以下内容。
from csv import writer
with open("data.csv", "w") as f:
wr = csv.writer(f)
# write column names
wr.writerow(["Day", "Date", "Teacher", "Note"])
for d in soup.find_all("div", class_="day"):
notes = d.find_all("div", class_="note")
teachers = d.find_all("div",class_="teacher")
date = d.find("div", class_="date")
times = d.find_all("div", class_="time")
day = d.find("h3",class_="dayname")
for note,time, teacher in zip(notes,times, teachers):
note_text = note.text
if "X2" in note_text:
# write each group on new row
wr.writerow((day.text, date.text, teacher.text,time.text, note.text))
但我只得到前两个节点。我不知道如何使用循环构建整个TreeView。
答案 0 :(得分:0)
输入示例
Root|A
Root|B|C
Root|B|D
Root|E
您的代码存在的问题是您只处理TreeNodes[0]
元素。处理需要循环的元素集合
public MainWindowVM()
{
private ObservableCollection<Node> mRootNodes;
public IEnumerable<Node> RootNodes { get { return mRootNodes; } }
string[] lines = null;
try
{
lines = System.IO.File.ReadAllLines(MainWindow.TextFilePath , System.Text.Encoding.Default);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
Environment.Exit(0);
}
if (lines == null || lines.Length == 0)
{
MessageBox.Show("Text file has no content!");
Environment.Exit(0);
}
Dictionary<string, Node> nodeCache = new Dictionary<string, Node>();
// processing each line
foreach (var line in lines)
{
Node parentNode = null;
string key = null;
// in each line there are one or more node names, separated by | char
foreach (string childNodeName in line.Split('|'))
{
Node childNode;
// names are not unique, we need a composite key (full node path)
key += "|" + childNodeName;
// each node has unique key
// if key doesn't exists in cache, we need to create new child node
if (false == nodeCache.TryGetValue(key, out childNode))
{
childNode = new Node { Name = childNodeName };
nodeCache.Add(key, childNode);
if (parentNode != null)
// each node (exept root) has a parent
// we need to add a child node to parent ChildRen collection
parentNode.Children.Add(childNode);
else
// root nodes are stored in a separate collection
mRootNodes.Add(childNode);
}
// saving current node for next iteration
parentNode = childNode;
}
}
}