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

3 回答 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)
              )
          )
      );
于 2010-11-16T22:44:07.323 回答
2

改用XmlWriter对象,至少在imo中更容易做你想做的事情。然后你可以像这样构造它:

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
于 2010-11-16T22:10:39.127 回答
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)
于 2010-11-16T22:34:15.563 回答