Altova XMLSpy 2023 Enterprise Edition

示例Schema生成代码后,将生成一个测试Java应用程序以及多个支持的Altova库。如上所述,示例Schema(Main.xsd)具有多个命名空间声明。因此,生成的代码包括与Schema中的命名空间别名(前缀)对应的命名空间,即:com.Main.ordcom.Main.purcom.Main.cmncom.Main.cust

 

通常,为了在Schema包装库的帮助下控制XML命名空间和前缀,您可以使用以下方法:

 

declareAllNamespacesFromSchema()。如果您想在XML实例中声明与Schema中相同的命名空间,请调用该方法。否则,如果您需要与本例中不同的命名空间,则应使用declareNamespace()。本例中未使用declareAllNamespacesFromSchema()方法,因为我们特意想要创建带有与Schema中声明的前缀稍有不同的前缀的XML元素。

declareNamespace().如果要在元素上创建或覆盖现有的命名空间前缀特性,则调用该方法。该元素必须已使用append()appendWithPrefix()方法创建,如下所示。

appendWithPrefix().使用此方法追加一个带有特定前缀的实例元素。要创建本例中展示的XML实例,仅需为根元素调用此方法。仅使用append()就可以追加所有其他元素,它们的前缀将根据上述规则基于其命名空间自动添加。

 

下方的代码片段向您展示了如何创建一个有多个命名空间声明和带前缀的元素名称的XML文档。具体来说,它会生成一个采购订单实例,如示例中所示:采购订单。重要的是,出于展示目的,XML实例中的一些前缀被覆盖(即,它们与Schema中声明的前缀并不完全相同)。

 

protected static void example() throws Exception {
  // Create the XML document and append the root element
  com.Main.pur.Main2 doc = com.Main.pur.Main2.createDocument();
  com.Main.pur.PurchaseType purchase = doc.Purchase.appendWithPrefix("p");
 
  // Set schema location
  doc.setSchemaLocation("Main.xsd");
 
  // Declare namespaces on root element
  purchase.declareNamespace("o", "http://NamespaceTest.com/OrderTypes");
  purchase.declareNamespace("c", "http://NamespaceTest.com/CustomerTypes");
  purchase.declareNamespace("cmn", "http://NamespaceTest.com/CommonTypes");
 
  // Append the OrderDetail element
  com.Main.ord.OrderType order = purchase.OrderDetail.append();
  com.Main.ord.ItemType item = order.Item.append();
  item.ProductName.append().setValue("Lawnmower");
  item.Quantity.append().setValue(1);
  java.math.BigDecimal price = new java.math.BigDecimal("148.42");
  item.UnitPrice.append().setValue(price);
 
  // Append the PaymentMethod element
  com.Main.cmn.PaymentMethodTypeType paymentMethod = purchase.PaymentMethod.append();
  paymentMethod.setEnumerationValue(com.Main.cmn.PaymentMethodTypeType.EVISA);
 
  // Append the CustomerDetails element
  com.Main.cust.CustomerType customer = purchase.CustomerDetails.append();
  customer.Name.append().setValue("Alice Smith");
  com.Main.cmn.AddressType deliveryAddress = customer.DeliveryAddress.append();
  deliveryAddress.Line1.append().setValue("123 Maple Street");
  deliveryAddress.Line2.append().setValue("Mill Valley");
  com.Main.cmn.AddressType billingAddress = customer.BillingAddress.append();
  billingAddress.Line1.append().setValue("8 Oak Avenue");
  billingAddress.Line2.append().setValue("Old Town");
 
  // Save to file
  doc.saveToFile("PurchaseOrder.xml", true);
}

© 2017-2023 Altova GmbH