我需要MyObject
类
public class MyObject{
public Long Amount {get; set}
public Long FiscalAmount {get; set;}
// .... A lot more of fields
}
例如,
MyObject.Amount
为5000,则预期结果为00005000。MyObject.FiscalAmount
为23,则预期结果为000023 为了完成这个,我定义了一个XML文件:
<FieldDescriptionXML>
<FielDefinition>
<Name>Amount</Name>
<FillWith>0</FillWith>
<Lenght>8</Lenght>
</FielDefinition>
<FielDefinition>
<Name>FiscalAmount</Name>
<FillWith>0</FillWith>
<Lenght>6</Lenght>
</FielDefinition>
.... A lot more of fields
<FieldDescriptionXML>
然后我使用以下代码获取具有所需输出的MyObject
字段
MyObject myObject = new MyObject();
myObject.Amount = 5000;
...
// Gets the xml definition
// I deserialize the previous XML file and name it FieldDescription
List<FieldDescription> fieldDescriptionList = DeserializeXML(XMLFilePath);
FieldDescription fieldDescription = fieldDescriptionList.Find(x => x.Name == "Amount");
// Apply the field definition and returns a string.
// For this I use a private method called ApplyXMLFielDefinition
// where I got how many spaces the result should be filled
string result = ApplyXMLFielDefinition(myObject.Amount,fieldDescription);
Console.Writeline(result) // prints 00005000
// Now same code for MyObject.FiscalAmount
如你所见,我得到了所需的输出,但我必须逐一重复代码。
还有其他更好的方法可以分享吗?谢谢。
环境:C#4.0
答案 0 :(得分:1)
如果我正确地阅读了您的问题,您将拥有一个要从大型xml集合中填充的元素列表。你试过LinqToXml
吗?var x = (from target in xmlDoc.Decendants("FielDefinition")
select (int) target.Element("FillWith").value()
where target.Element("Name").Value.tolower() == "amount")).ToList();
这将返回list<int>