2 回答

TA貢獻1804條經驗 獲得超8個贊
您可以使用File
類中的靜態方法非常輕松地寫入文本文件,因為它為您包裝了流創建。
首先,我們可以重寫上面的方法以返回 a List<string>
,然后可以將其寫入控制臺或文件或其他任何內容:
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;
}
現在,我們可以使用此方法獲取節點信息,然后將其寫入我們想要的任何內容:
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貢獻2016條經驗 獲得超9個贊
我剛剛找到了問題的答案。我使用了以下內容:
使用 (FileStream f = new FileStream(fileName, FileMode.Append, FileAccess.Write)) 使用 (StreamWriter s = new StreamWriter(f))
對于每個 Console.Writline 更改為
s.WriteLine
- 2 回答
- 0 關注
- 119 瀏覽
添加回答
舉報