我發現本指南中,我的XML文件轉換爲CSV文本:https://msdn.microsoft.com/en-us/library/mt693157.aspx具有相同名稱的轉換節點用C#
一切安好,直到節點的部分具有相同的名稱
<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」 - 它崩潰。現在我只需要繞過這個莫名其妙
而具體的錯誤信息是? –
使用「元素(」屬性「)」不是「元素(」屬性「)」(字符串)el.Element(「ProductSpecification」)。元素(「屬性」) – Vijai
Luc,我得到這個:'System.NullReferenceException未處理 HResult = -2147467261 Message =對象引用未設置爲對象的實例。# – tdesws