2010-11-16 58 views
4

我必須根據用戶輸入動態地創建一個XML文件。使用c動態構建XML

這是我想出來的,我有兩個問題。

  1. 如果有相同元素的集合(maxOccurs的= 10) (例如,如果用戶輸入4個帳戶然後我的代碼應如何)
  2. 如果有一個選擇的選項。根據所選元素,子元素應該改變。

有人請幫幫我。

在此先感謝

BB

我的代碼:

XElement req = 
    new XElement("order", 
     new XElement("client", 
      new XAttribute("id", clientId), 
      new XElement("quoteback", 
       new XAttribute ("name",quotebackname) 
       ) 
      ), 
     new XElement("accounting", 
      new XElement("account"), 
      new XElement("special_billing_id") 
      ), 
     new XElement("products", 
      new XElement(
       **productChoiceType**, 
       ***** HERE THE ELEMENTS WILL CHAGE BASED ON **productChoiceType**   
       ) 
      ) 
     ) 
    ); 

回答

6

LINQ就派上用場了這樣的事情:

XElement req = 
    new XElement("order", 
     new XElement("client", 
      new XAttribute("id",clientId), 
      new XElement("quoteback", new XAttribute ("name",quotebackname)) 
      ), 
     new XElement("accounting", 
      new XElement("account"), 
      new XElement("special_billing_id") 
      ), 
      new XElement("products", 
       new XElement(productChoices.Single(pc => pc.ChoiceType == choiceType).Name, 
        from p in products 
        where p.ChoiceType == choiceType 
        select new XElement(p.Name) 
      ) 
     ) 
    ); 
+0

StriplingWarrior非常感謝你。根據(p.Name)的選擇,我必須爲「產品」添加一組完整的元素。 – BumbleBee 2010-11-16 23:02:57

+0

說如果p.Name是CLUEAuto那麼我必須添加參數,pnc,使用元素到「產品」。如果p.Name是Mortgae,那麼我必須將參數RiskAddress,CurrentAddress,PreviousAddress,Mortgage元素添加到產品 – BumbleBee 2010-11-16 23:10:49

+0

new XElement(「parameter」),new XElement(「pnc」),new XElement(「usage」,ClueAutoUsageEnum), – BumbleBee 2010-11-16 23:11:42

1

使用的XmlWriter對象,而不是,至少國際海事組織很容易做的那種你想要的東西。然後,您可以像這樣構建它:

XmlWriter w = XmlWriter.Create(outputStream); 
w.WriteStartElement("order"); 

w.WriteStartElement("client"); 
w.WriteAttributeString("id", clientId); 

// ... 
w.WriteElementString("product", "1"); 
w.WriteElementString("product", "2"); 
w.WriteElementString("product", "3"); 
w.WriteElementString("product", "4"); 

// etc.... 

w.WriteEndElement(); // client 

w.WriterEndElement(); // order 
0

或者爲每個要轉換爲XML並使用XmlSerializer的類型創建一個類。

<XmlElement("order")> _ 
Public Class Order 
    <XmlElement("accounting")> _ 
    Dim accounts As List(Of Account) 
    ... 
End Class 

Dim xmlSer as New XmlSerialzer(GetType(Accounting)) 
xmlSer.Serialize(myXmlWriter, myObjInstance)