Altova XMLSpy 2023 Enterprise Edition

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

 

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

 

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

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

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

 

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

 

void Example()
{
  // Create the XML document and append the root element
  Main::pur::CMain doc = Main::pur::CMain::CreateDocument();
  Main::pur::CPurchaseType purchase = doc.Purchase.appendWithPrefix(_T("p"));
 
  // Set schema location
  doc.SetSchemaLocation(_T("Main.xsd"));
 
  // Declare namespaces on root element
  purchase.DeclareNamespace(_T("o"), _T("http://NamespaceTest.com/OrderTypes"));
  purchase.DeclareNamespace(_T("c"), _T("http://NamespaceTest.com/CustomerTypes"));
  purchase.DeclareNamespace(_T("cmn"), _T("http://NamespaceTest.com/CommonTypes"));
 
  // Append the OrderDetail element
  Main::ord::COrderType order = purchase.OrderDetail.append();
  Main::ord::CItemType item = order.Item.append();
  item.ProductName.append() = _T("Lawnmower");
  item.Quantity.append() = 1;
  item.UnitPrice.append() = 148.42;
 
  // Append the PaymentMethod element
  Main::cmn::CPaymentMethodTypeType paymentMethod = purchase.PaymentMethod.append();
  paymentMethod.SetEnumerationValue(Main::cmn::CPaymentMethodTypeType::k_VISA);
 
  // Append the CustomerDetails element
  Main::cust::CCustomerType customer = purchase.CustomerDetails.append();
  customer.Name.append() = _T("Alice Smith");
  Main::cmn::CAddressType deliveryAddress = customer.DeliveryAddress.append();
  deliveryAddress.Line1.append() = _T("123 Maple Street");
  deliveryAddress.Line2.append() = _T("Mill Valley");
  Main::cmn::CAddressType billingAddress = customer.BillingAddress.append();
  billingAddress.Line1.append() = _T("8 Oak Avenue");
  billingAddress.Line2.append() = _T("Old Town");
 
  // Save to file and release object from memory
  doc.SaveToFile(_T("Main1.xml"), true);
  doc.DestroyDocument();  
}

© 2017-2023 Altova GmbH