第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

控制臺能夠顯示所有導(dǎo)入的 XML 數(shù)據(jù),但不能將所有信息發(fā)送到文本文件

控制臺能夠顯示所有導(dǎo)入的 XML 數(shù)據(jù),但不能將所有信息發(fā)送到文本文件

C#
倚天杖 2022-12-04 13:21:35
我有以下代碼從 XML 文件收集所有元素和屬性并發(fā)送到控制臺。這沒有問題。我想將數(shù)據(jù)發(fā)送到文本文件,但只顯示第一行或最后一行。有沒有人對將數(shù)據(jù)發(fā)送到 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貢獻(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);


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

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


查看完整回答
反對 回復(fù) 2022-12-04
  • 2 回答
  • 0 關(guān)注
  • 110 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號