65.9K
CodeProject 正在变化。 阅读更多。
Home

XML 按 Schema

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.17/5 (6投票s)

2002年9月27日

2分钟阅读

viewsIcon

77782

downloadIcon

2062

使用 XML 模式验证 XML。

Sample Image - sample.jpg

描述

此应用程序用于根据 XML 模式验证 XML 文件。这需要 MSXML 库(4.0 或更高版本);请注意其中的错误并更新到最新版本或 Service Pack!

用法

集合

是一个存储区域,您可以在其中添加 <命名空间,模式> 对(有关 XML 模式和 IXMLDOMSchemaCollection 的更多信息,请查阅 MSDN)。基本上,您提供与模式相关的命名空间。命名空间在集合中应该是唯一的,而模式应该出现在几个不同的对中。

状态

每次操作后,请查看此框,以查看操作是否成功。

插入配对

在最上面的编辑框中写入模式的 URN。您可以按打开从本地机器打开它。在相应的编辑框(组合框)中写入命名空间。按插入到集合。请注意,命名空间可以是空字符串或完全由空格组成。插入一个已存在于集合中的命名空间将更新关联的模式的内容。每次修改模式文件时,您都必须这样做。如果插入命名空间到集合失败,而该命名空间已存在,则上次成功插入的模式将保持活动状态。

移除配对

仅使用命名空间即可完成。键入它或从组合框中选择它,然后按从集合中移除

移除所有配对

只需按清空整个集合

验证 XML

在最上面的编辑框中写入 XML 文件的 URN 或打开它。按验证为 XML

浏览器

用于显示参与验证过程的文件内容。您也可以像使用 IE 一样使用它(例如,查看和修改源代码)。

IXMLDOMSchemaCollection 的使用

代码来自 ValidatorDlg.cpp

创建

BOOL CValidatorDlg::OnInitDialog()
{
  // ...

  HRESULT hr2, hr1=m_doc.CoCreateInstance(__uuidof(DOMDocument));
  hr2=m_schema.CoCreateInstance(__uuidof(XMLSchemaCache));
  if (hr1!=S_OK || hr2!=S_OK)
  {
    MessageBox("Creating COM objects failure!\r\n"
      "Make sure you have installed MSXML 4.0 on your machine!",
      "XMLbyXSD");
    PostQuitMessage(0);
  }
  VARIANT var;
  var.vt = VT_DISPATCH;
  var.pdispVal = m_schema.p;
  if (m_doc->putref_schemas(var)!=S_OK) // associate schema with document

  {
    MessageBox("COM operation failed!", "XMLbyXSD");
    PostQuitMessage(0);
  }
  m_doc->put_async(VARIANT_FALSE);
  m_doc->put_validateOnParse(VARIANT_TRUE);
  // ...

}

配对插入

void CValidatorDlg::OnButtonAdd() 
{
  CString szMan, szUrn;
  // ...

  try
  {
    // adding <namespace, schema> pair to collection

    m_schema->add(_bstr_t(szMan), _variant_t(szUrn)); 
    // ...

  }
  catch (_com_error &x) // attempt failed!  

  {
    PrintStatus("Schema error!", (char *)x.Description(), 
      0, NULL); 
    return;
  }
}

命名空间移除

void CValidatorDlg::OnButtonRemove() 
{
  CString szMan;
  // ...

    try
    {
      // remove namespace+schema from collection

      m_schema->remove(_bstr_t(szMan)); 
    }
    catch (_com_error &x) // attempt failed

    {
      PrintStatus("Removing schema error!", (char *)x.Description(), 
        0, NULL);
      return;
    }
  // ...

}

验证

void CValidatorDlg::OnButtonValidate() 
{
  BSTR bs;
  CString szReason, szText;
  // ...

  // associated schema collection will accomplish its task

  m_doc->load(_variant_t(szText)); 
  IXMLDOMParseError *pErr=NULL;
  if (m_doc->get_parseError(&pErr)==S_OK)
    if (pErr)
    {
      pErr->get_errorCode(&ln);
      if (ln) // errors

      {
        // ...

      }
      else
        PrintStatus("XML is valid according to "
        "collection content!", NULL, ln, NULL);
      pErr->Release();
    }
}

更新

  • 2002 年 9 月 30 日 - 修复了错误。
© . All rights reserved.