使用c#动态构建XML

4
我需要根据用户输入动态创建一个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**           
                )
            )
        )
    );
3个回答

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)
              )
          )
      );

StriplingWarrior 非常感谢。根据所选的 (p.Name),我需要向“产品”添加完全不同的元素集。 - BumbleBee
如果p.Name是CLUEAuto,那么我必须将参数pnc、usage元素添加到“products”中。如果p.Name是Mortgae,则我必须将参数RiskAddress、CurrentAddress、PreviousAddress、Mortgage元素添加到Products中。 - BumbleBee
new XElement("parameter"), new XElement("pnc"), new XElement("usage", ClueAutoUsageEnum), - BumbleBee
1
@BumbleBee:应用你看到我使用的相同原则:...new XElement(p.Name, from t in thingRepository.GetByProductName(p.Name) select new Element(t.Whatever) - StriplingWarrior

2

建议使用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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接