2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用File
類中的靜態(tài)方法非常輕松地寫入文本文件,因?yàn)樗鼮槟b了流創(chuàng)建。
首先,我們可以重寫上面的方法以返回 a List<string>
,然后可以將其寫入控制臺或文件或其他任何內(nèi)容:
public static List<string> GetNodeInfo(XmlNode node)
{
if (node == null) return new List<string>();
var nodes = new List<string>
{
node.NodeType == XmlNodeType.Text
? node.Value.TrimStart()
: node.Name.TrimStart()
};
if (node.Attributes != null)
{
nodes.AddRange(node.Attributes.Cast<XmlAttribute>()
.Select(attribute => $"{attribute.Name} {attribute.Value}\n"));
}
nodes.AddRange(node.ChildNodes.Cast<XmlNode>().SelectMany(GetNodeInfo));
return nodes;
}
現(xiàn)在,我們可以使用此方法獲取節(jié)點(diǎn)信息,然后將其寫入我們想要的任何內(nèi)容:
List<string> nodeInfo = GetNodeInfo(myNode);
// Write it to the console:
Console.WriteLine(string.Join(Environment.NewLine, nodeInfo));
// Write it to a file:
File.WriteAllLines(myFilePath, nodeInfo);

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
我剛剛找到了問題的答案。我使用了以下內(nèi)容:
使用 (FileStream f = new FileStream(fileName, FileMode.Append, FileAccess.Write)) 使用 (StreamWriter s = new StreamWriter(f))
對于每個(gè) Console.Writline 更改為
s.WriteLine
- 2 回答
- 0 關(guān)注
- 110 瀏覽
添加回答
舉報(bào)