使用c#将同名节点转换为文本
本文关键字:转换 文本 节点 使用 | 更新日期: 2023-09-27 18:02:04
我找到了这个指南,将我的xml文件转换为csv: https://msdn.microsoft.com/en-us/library/mt693157.aspx
一切正常,直到部分节点具有相同的名称
<ProductSpecification>
<Property>
<Name>CLEANING PERFORMANCE</Name>
<Value>-</Value>
</Property>
<Property>
<Name>COLOUR</Name>
<Value>White</Value>
</Property>
<Property>
<Name>DIMENSIONS (H x W x D cm)</Name>
<Value>85 x 60 x 45</Value>
</Property>
<Property>
<Name>DISH SETTING CAPACITY</Name>
<Value>-</Value>
</Property>
</ProductSpecification>
如果我尝试使用
(string)el.Element("ProductSpecification"),
我的整个文本合并成一大堆字母,节点之间没有任何空格:
CLEANING PERFORMANCE-COLOURWhiteDIMENSIONS (H x W x D cm)85 x 60 x 45DISH SETTING CAPACITY-
如果我尝试使用
(string)el.Element("ProductSpecification").Element("Property"),
我只是得到一个错误,没有任何解释是什么错误
我需要的结果是:
Cleaning Performance
-
Colour
White
秀……我试了所有我能想到的方法,但就是写不出结点之间有空格的文字编辑:现在添加我的整个脚本:
XElement custOrd = XElement.Load("_output.xml");
string csv =
(from el in custOrd.Elements("PriceCatalog").Elements("ListofCatalogDetails").Elements("CatalogItem").Elements("Product").Elements("ProductSpec").Elements("ProductDetails")
select
String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16}, '"{17}'"{18}",
(string)el.Element("ProductID"),
(string)el.Element("PartNumber"),
(string)el.Element("Description"),
(string)el.Element("LongDesc"),
(string)el.Element("Manufacturer"),
(string)el.Element("Category01"),
(string)el.Element("Category02"),
(string)el.Element("Category03"),
(string)el.Element("CategoryVAT"),
(string)el.Element("PeriodofWarranty"),
(string)el.Element("Qty").Element("QtyAvailable"),
(string)el.Element("UnitPrice"),
(string)el.Element("VatRate"),
(string)el.Element("Weight"),
(string)el.Element("Height"),
(string)el.Element("Width"),
(string)el.Element("Length"),
(string)el.Element("ProductSpecification"),
Environment.NewLine
)
)
.Aggregate(
new StringBuilder(),
(sb, s) => sb.Append(s),
sb => sb.ToString()
);
Console.WriteLine(csv);
EDIT02:我刚刚发现有些项目没有"ProductSpecification"节点,但是c#没有给出任何错误,但是如果我使用"ProductSpecification"。Property"——它崩溃了。现在我需要绕过这个
您可以像这样遍历XML:
var doc = XDocument.Parse(xml);
foreach (var property in doc.Element("ProductSpecification").Elements("Property"))
{
foreach(var element in property.Descendants())
{
Console.WriteLine(element.Value);
}
}
这将产生以下结果:
CLEANING PERFORMANCE
-
COLOUR
White
DIMENSIONS (H x W x D cm)
85 x 60 x 45
DISH SETTING CAPACITY
试试这个,我还没有调试过
XElement custOrd = XElement.Load("yourxml.xml");
string csv =
(from el in custOrd.Element("ProductSpecification").Elements("Property")
select
String.Format("{0},{1}",
(string)el.Element("Name"),
(string)el.Element("Value"),
Environment.NewLine
)
)
.Aggregate(
new StringBuilder(),
(sb, s) => sb.Append(s),
sb => sb.ToString()
);
Console.WriteLine(csv);