2011-05-18 64 views
2

輸入:添加使用的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 

    )); 

任何其他技術來做到這一點像字符串操作或正則表達式代替?

回答

2

您不希望爲列使用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> 
+0

謝謝。我添加了對數據的錯誤檢查,因爲如果選項卡放置不正確,可能會出現數組索引超出範圍的異常。 – 2011-05-18 23:27:15