亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

控制臺能夠顯示所有導入的 XML 數據,但不能將所有信息發送到文本文件

控制臺能夠顯示所有導入的 XML 數據,但不能將所有信息發送到文本文件

C#
倚天杖 2022-12-04 13:21:35
我有以下代碼從 XML 文件收集所有元素和屬性并發送到控制臺。這沒有問題。我想將數據發送到文本文件,但只顯示第一行或最后一行。有沒有人對將數據發送到 txt 文件有任何建議?XmlDocument xmlDoc = new XmlDocument();         xmlDoc.Load(path);XmlNode rootNode = xmlDoc.DocumentElement;DisplayNodes(rootNode);Console.ReadLine();void DisplayNodes(XmlNode node){    //Print the node type, node name and node value of the node    if (node.NodeType == XmlNodeType.Text)    {         Console.WriteLine(node.Value.TrimStart());        }    else    {        Console.WriteLine(node.Name.TrimStart());    }    //Print attributes of the node    if (node.Attributes != null)    {                                XmlAttributeCollection attrs = node.Attributes;        foreach (XmlAttribute attr in attrs)        {              Console.WriteLine(attr.Name + " " + attr.Value + "\n");        }    }    XmlNodeList children = node.ChildNodes;    foreach (XmlNode child in children)    {          DisplayNodes(child);    }}
查看完整描述

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);


查看完整回答
反對 回復 2022-12-04
?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

我剛剛找到了問題的答案。我使用了以下內容:

使用 (FileStream f = new FileStream(fileName, FileMode.Append, FileAccess.Write)) 使用 (StreamWriter s = new StreamWriter(f))

對于每個 Console.Writline 更改為

s.WriteLine


查看完整回答
反對 回復 2022-12-04
  • 2 回答
  • 0 關注
  • 119 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號