我正在尝试将 xml 文件的属性解析为 csv 文件,代码检查并运行时没有错误,并且生成了输出 CSV 文件,但不包含任何数据我认为问题可能在于元素的附加,因为当我尝试将另一个声明的字符串附加到字符串生成器时,它仍然没有打印出任何内容。我也尝试过更改后代,以防万一这里出现错误,但似乎没有任何效果using System;using System.Linq;using System.Xml.Linq;using System.IO;using System.Text;namespace Test{ class Program { public static void Main() { StringBuilder sb = new StringBuilder(); string delimiter = ","; XDocument.Load(@"C:\Users\livingss\Desktop\XML - CSV\xml\Xml\----------.xml").Descendants("Param").ToList().ForEach( element => sb.Append(element.Attribute("Name").Value + delimiter + element.Attribute("PNum").Value + "\r\n")); Console.WriteLine(sb); StreamWriter sw = new StreamWriter(@"C:\Users\livingss\Desktop\XML - CSV\Result.csv"); sw.WriteLine(sb.ToString()); sw.Close(); } }}<?xml version="1.0" encoding="utf-8"?><Equipment EType="0000" Name="PlaceHolder" Version="$Revision: 2$" xmlns="urn:equipment-type"> <EqAttributes /> <EqVariant /> <EqModules /> <EqLogging /> <EqParameters> <Param Name="Not Used" PNum="1"> <Desc>Spare</Desc> </Param> <Param Name="Equipment Status" PNum="2" Min="0" Max="8" Un="1"> <vMap> <Opt Name="Stopped">0</Opt> <Opt Name="Starting">1</Opt> <Opt Name="Running">2</Opt> <Opt Name="Stopping">3</Opt> <Opt Name="Standby">4</Opt> <Opt Name="Idle">5</Opt> <Opt Name="Sleep">6</Opt> <Opt Name="Hibernate">7</Opt> <Opt Name="Faulted">8</Opt> </vMap> </Param> <Param Name="Not Used" PNum="3" Min="0" Max="5" Un="3"> <Desc>Spare</Desc> </Param> </EqParameters> <EqConfiguration> </EqConfiguration></Equipment>预期输出应该是 Param 的属性,即“Name”和“PNum”,第一行的输出应该是“NotUsed,1”
3 回答
慕仙森
TA贡献1827条经验 获得超7个赞
您应该添加命名空间并在Descendants
调用中使用它:
XNamespace urn="urn:equipment-type"; XDocument.Load(filePath).Descendants(urn + "Param").ToList().ForEach(...
如果没有名称空间,我也无法枚举任何结果。
慕的地8271018
TA贡献1796条经验 获得超4个赞
对我来说,问题在于你编写文件的方式。尝试替换它:
StreamWriter sw = new StreamWriter(@"C:\Users\livingss\Desktop\XML - CSV\Result.csv"); sw.WriteLine(sb.ToString()); sw.Close();
接着就,随即:
var path = @"C:\Users\livingss\Desktop\XML - CSV\Result.csv"; File.WriteAllText(path, sb.ToString());
慕森卡
TA贡献1806条经验 获得超8个赞
就这样吧!
StringBuilder sb = new StringBuilder();
string delimiter = ",";
XmlDocument doc = new XmlDocument();
doc.Load(@"file.xml");
var paramElements = doc.GetElementsByTagName("Param");
for (int i = 0; i < paramElements.Count; i++)
{
var currentElt = paramElements.Item(i);
sb.Append(currentElt.Attributes.GetNamedItem("Name").Value);
sb.Append(delimiter);
sb.Append(currentElt.Attributes.GetNamedItem("PNum").Value);
sb.AppendLine();
}
var path = @"Result.csv";
File.WriteAllText(path, sb.ToString());
- 3 回答
- 0 关注
- 110 浏览
添加回答
举报
0/150
提交
取消