添加使用的XElement select语句的许多元素
问题描述:
输入:添加使用的XElement select语句的许多元素
"CustomerName Details 121.11.2222 Address-Line1,City,State 36,EU \r
Customer1 SomeDetails 911.911.911 ABCD Street, Some Lane, Some City, Some State 50,USA \n
"
我要生成一个像这样的XML:
<Customers>
<Customer>
<Name>CustomerName</Name>
<Details>Details</Details>
<Phone>121.11.2222</Phone>
<AddressDetails>
<Address>Address-Line1</Address>
<Address>City</Address>
<Address>State</Address>
</AddressDetails>
<PersonalDetails>
<Age>36</Age>
<Nation>EU</Nation>
</PersonalDetails>
</Customer>
<Customer>
....
</Customer>
</Customers>
的好处是,输入字符串始终遵循所有相同的格式行集。
试图像这样使用LINQ,我碰到困难时,我试图创建在相同的选择多于一个的XElement(见下文):
string inputString ="CustomerName Details 121.11.2222 Address-Line1,City,State 36,EU \r Customer1 SomeDetails 911.911.911 ABCD Street, Some Lane, Some City, Some State 50,USA \n ";
string[] inputRow = inputString.Split('\n');
var root = new XElement("Customers",
from customerRowSet in inputRow
select new XElement("Customer",
from column in customerRowSet.Split('\t') //Assume columns are tab seperated
select
new XElement("Name", column),
// new XElement("Details", column[1]), Need to add to XML here, but error is thrown on attempt
from commafilters in customerRowSet.Split(',')
select new XElement("AddressDetails", commafilters) //Not sure how to filter out Address[x] seperate from PersonalDetails[y] as both come in comma-seperated
));
任何其他技术来做到这一点像字符串操作或正则表达式代替?
答
您不希望为列使用LINQ,因为您希望以不同的方式处理每列。你可以做的是这样的:
var root = new XElement("Customers",
from customerRowSet in inputRow
let columns = customerRowSet.Split('\t') //Assume columns are tab seperated
select new XElement("Customer",
new XElement("Name", columns[0]),
new XElement("Details", columns[1]),
new XElement("Phone", columns[2]),
new XElement("Address",
from commafilters in columns[3].Split(',')
select new XElement("AddressDetails", commafilters.TrimStart())
)));
产生以下XML:
<Customers>
<Customer>
<Name>CustomerName</Name>
<Details>Details</Details>
<Phone>121.11.2222</Phone>
<Address>
<AddressDetails>Address-Line1</AddressDetails>
<AddressDetails>City</AddressDetails>
<AddressDetails>State</AddressDetails>
</Address>
</Customer>
<Customer>
<Name>Customer1</Name>
<Details>SomeDetails</Details>
<Phone>911.911.911</Phone>
<Address>
<AddressDetails>ABCD Street</AddressDetails>
<AddressDetails>Some Lane</AddressDetails>
<AddressDetails>Some City</AddressDetails>
<AddressDetails>Some State</AddressDetails>
</Address>
</Customer>
</Customers>
谢谢。我添加了对数据的错误检查,因为如果选项卡放置不正确,可能会出现数组索引超出范围的异常。 – 2011-05-18 23:27:15