为了账号安全,请及时绑定邮箱和手机立即绑定

控制台能够显示所有导入的 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 关注
  • 64 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信