[英]Export model to text file with out column names or headers(only values)
我有一個DTO(數據傳輸對象)對象作為模型,其中包含來自收到的響應的數據。 我只需要將標題/列下的值導出到文本文件。 列名或標題無需導出。 我可以借助XmlSerializer
以XML格式導出數據。 但是找不到任何文本序列化程序。 我的模型如下:
public class ResponseGradeDto
{
[XmlIgnore]
[XmlElement(ElementName = "GRADEID")]
public Guid Id { get; set; }
[XmlElement(ElementName = "GRADENAME")]
public string Name { get; set; }
[XmlElement(ElementName = "GRADECODE")]
public string Code { get; set; }
public List<GradeQualitySpecDto> QualitySpecItem { get; set; }
}
我嘗試下面的代碼:
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(responseGradeDto.GetType());
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, responseGradeDto);
string a = textWriter.ToString();
return textWriter.ToString();
}
假設我的模型如下:
{
"name": "My Name",
"code": "1234",
"information": "My Info",
"gradeQualitySpecItem": [
{
"propertyid": "100",
"propertyname": "PropertyName1",
"target": 10,
"sigma": 20
},
{
"propertyid": "200",
"propertyname": "PropertyName2",
"target": 10,
"sigma": 30
}]
}
我需要在文本文件中輸出如下:
AL300 SAMPLE(Some hard coded text)
My Name
1234
My Info
PROP-SUMMARY
100
PropertyName1
10
20
PROP-SUMMARY
200
PropertyName2
10
30
end AL300 SAMPLE(end of file)
如果是列表,我將在列表的輸出下方。 有人可以幫我嗎?
沒有內置的“純文本”序列化程序可將對象屬性值序列化為以行分隔的文本。 大多數情況下,當您要將對象保存為文本時,只需編寫代碼即可。
例:
var x = new ResponseGradeDto{
Id = Guid.NewGuid(),
Name = "Foo",
Code = "Cde",
Information = "No info"
};
using (var writer = new StreamWriter(@"C:\temp\log.txt"))
{
writer.WriteLine(x.Name);
writer.WriteLine(x.Code);
writer.WriteLine(x.Information);
}
但是,一種更通用的方法是使用反射來獲取對象的所有引用屬性:
var properties = typeof(ResponseGradeDto).GetProperties();
然后將屬性轉儲到文件中可能很簡單(請注意,我使用了上面代碼中定義的對象x
):
File.WriteAllLines(@"C:\temp\attr.txt", properties.Select(p => p.GetValue(x).ToString()));
如果願意,可以將屬性與上面的反射解決方案一起使用,以過濾掉所需的/不需要的屬性。 在這里,我重復使用您在示例中使用的“ Xml屬性”,您可以編寫自己的屬性:
var properties = typeof(ResponseGradeDto).GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(XmlElementAttribute))
&& !Attribute.IsDefined(prop, typeof(XmlIgnoreAttribute))
);
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.