假设你要生成如下的 Xml
<Root>
<JustTest />
<Request>
<Source>
<RequestorID RequestorID="1483" EMailAddress="M@C.IE" Password="XXX" />
<RequestorPreferences Language="en" Currency="USD">
<RequestMode>SYNCHRONOUS</RequestMode>
</RequestorPreferences>
</Source>
<RequestDetails>
<AddBookingRequest Currency="USD">
<BookingName>MC20031301</BookingName>
<BookingReference>MC20031301</BookingReference>
<BookingDepartureDate>2017-02-28</BookingDepartureDate>
<PaxNames>
<PaxName PaxId="1"><![CDATA[Mr aa bb]]></PaxName>
<PaxName PaxId="2"><![CDATA[Mrs cc bb]]></PaxName>
</PaxNames>
<BookingItem ItemType="hotel" ExpectedPrice="50.0">
<ItemReference>1</ItemReference>
<ItemCity Code="AMS" />
<Item Code="NAD" />
<HotelItem>
<PeriodOfStay>
<CheckInDate>2017-03-10</CheckInDate>
<CheckOutDate>2017-03-12</CheckOutDate>
</PeriodOfStay>
<HotelRooms>
<HotelRoom RoomIndex="1" Code="TB" Id="001:ABC" />
<HotelRoom RoomIndex="2" Code="TB" Id="001:ABC" />
</HotelRooms>
</HotelItem>
</BookingItem>
</AddBookingRequest>
</RequestDetails>
</Request>
</Root>
你要怎么办呢?
用字符串? 太落!还会被人笑话!
用替换?太麻烦,还不如用模板。
用模板?我要改了属性名称字呢?我要改了类结构呢?
那定义实体类呢?
看这个XML的结构了没有?定义类?自找苦吃啊,出力不讨好!
那有没有简便的方法呢?
有,我都给你写好了!
var names = new List<string>() {
"Mr aa bb",
"Mrs cc bb"
};
var roomCount = 2;
var data = new {
JustTest = FluentXmlEmptyElement.Create(),
RequestOn = DateTime.Now.AsIgnore(),
Request = new {
Source = new {
RequestorID = new {
RequestorID = "1483".AsAttribute(),
EMailAddress = "M@C.IE".AsAttribute(),
Password = "XXX".AsAttribute(),
},
RequestorPreferences = new {
Language = "en".AsAttribute(),
Currency = "USD".AsAttribute(),
RequestMode = "SYNCHRONOUS"
}
},
RequestDetails = new {
AddBookingRequest = new {
Currency = "USD".AsAttribute(),
BookingName = "MC20031301",
BookingReference = "MC20031301",
BookingDepartureDate = DateTime.Now.AsElement("yyyy-MM-dd"),
PaxNames = names.Select((n, i) => new {
PaxId = (i + 1).AsAttribute(),
Value = n.AsElementValue()
}).AsElementArray("PaxName"),
BookingItem = new {
ItemType = "hotel".AsAttribute(),
ExpectedPrice = 50.0M.AsAttribute(),
ItemReference = 1,
ItemCity = new {
Code = "AMS".AsAttribute()
},
Item = new {
Code = "NAD".AsAttribute()
},
HotelItem = new {
PeriodOfStay = new {
CheckInDate = DateTime.Now.AddDays(10).AsElement("yyyy-MM-dd"),
CheckOutDate = DateTime.Now.AddDays(12).AsElement("yyyy-MM-dd")
},
HotelRooms = Enumerable.Range(1, roomCount).Select(i => new {
RoomIndex = i.AsAttribute(),
Code = "TB".AsAttribute(),
Id = "001:ABC".AsAttribute()
}).AsElementArray("HotelRoom")
}
}
}
}
}
};
var xml = FluentXmlHelper.Build(data, "Root");
var xmlStr = xml.ToString();
FluentXml 提供如下扩展属性:
- AsAttribute : 值做为属性输出
- AsElement : 值做为节点输出
- AsElementValue : 同 AsElement,但是适用于那种即有属性又有值的 xml 节点。
- AsElementArray : 值做为子节点集合输出。
- AsIgnore : 不输出(辅助)
- SetFormat : 设置输出格式
- SetNullVisible : 默认的,如果值为 null ,就不会输出该节点/属性。如果设置 NullVisible , 将输出值为 null 的节点/属性
- Build
还有 FluentXmlEmptyElement.Create() 用于创建一个即没有属性,也没有值的节点!!