您好我正在使用此代码解析我的XML
文档
XDocument doc = XDocument.Load(path);
XElement person = doc.Descendants().Where(x => x.Name.LocalName == "Person").FirstOrDefault();
XNamespace ns = person.GetDefaultNamespace();
Dictionary<string, string> dict = person.Elements()
.Where(x => x.Name.LocalName != "IdDocumentList")
.GroupBy(x => x.Name.LocalName, y => y == null ? "" : (string)y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
foreach (XElement element in person.Descendants(ns + "IdDocument").FirstOrDefault().Elements())
{
dict.Add(element.Name.LocalName, (string)element);
}
在dict中,字段键DateOfBirth
的格式为yyyy-mm-dd
。
如何将此字段重新格式化为dd-mm-yyyy
?
执行代码
后,这是dict的值- dict Count = 14 System.Collections.Generic.Dictionary<string, string>
+ [0] {[PersonObjectId, 111111111]} System.Collections.Generic.KeyValuePair<string, string>
+ [1] {[CellPhoneNo, 1212121212 ]} System.Collections.Generic.KeyValuePair<string, string>
+ [2] {[DateOfBirth, 1971-03-06]} System.Collections.Generic.KeyValuePair<string, string>
+ [3] {[Email, xxxxx@yahoo.com ]} System.Collections.Generic.KeyValuePair<string, string>
+ [4] {[EMBG, 12122121212]} System.Collections.Generic.KeyValuePair<string, string>
+ [5] {[IsResident, 1]} System.Collections.Generic.KeyValuePair<string, string>
+ [6] {[FirstName, xxx]} System.Collections.Generic.KeyValuePair<string, string>
+ [7] {[GenderTypeId, 3]} System.Collections.Generic.KeyValuePair<string, string>
+ [8] {[LastName, xxxxx]} System.Collections.Generic.KeyValuePair<string, string>
+ [9] {[PhoneNo, ]} System.Collections.Generic.KeyValuePair<string, string>
+ [10] {[PlaceOfBirth, ]} System.Collections.Generic.KeyValuePair<string, string>
+ [11] {[IdDocumentTypeId, 2]} System.Collections.Generic.KeyValuePair<string, string>
+ [12] {[PlaceOfIssue, xxxxx ]} System.Collections.Generic.KeyValuePair<string, string>
+ [13] {[IdNo, xxx]} System.Collections.Generic.KeyValuePair<string, string>
+ Raw View
sql null string
正如我所说,我只想重新格式化DateOfBirth字段
答案 0 :(得分:1)
选择每个键的值时,检查它是否为DateOfBirth
记录。如果是,则解析为DateTime
并使用ToString
获取所需格式
var dict = person.Elements()
.Where(x => x.Name.LocalName != "IdDocumentList")
.GroupBy(x => x.Name.LocalName, y => y == null ? "" : (string)y)
.ToDictionary(x => x.Key,
y => y.Key == "DateOfBirth" ?
DateTime.ParseExact(y.FirstOrDefault(),"yyyy-mm-dd",null).ToString("dd-mm-yyyy") :
y.FirstOrDefault());
但是我认为更好的解决方案一起将创建一个具有这些属性的自定义类,然后从xml中创建它的对象。看看