问题
· 五月 6, 2021

M里面如何获取xml文件的编码说明以及节点的说明注释等

如这文件内容 <?xml version="8.0"?>
<root xmlns="test" xmlns:mc="test1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="test2">
    <!--这个是说明测试哦-->
    <id code="test3"/><root>

我需要获取到<?xml version="8.0"?> 以及 root 节点的所有属性和他们的值比如xmlns,它的值是test,需要获取到id的说明 内容“这个是说明测试哦”

产品版本: Ensemble 2016.1
$ZV: Cache for Windows (x86-64) 2016.2.3 (Build 907_11_20446U) Thu Nov 12 2020 16:56:45 EST
讨论 (4)2
登录或注册以继续

在Caché ObjectScript语言里, 有两个class处理XML内容比较合适。 一个是%XML.Document,把xml读到里面可以用GetVersion(), GetNamespace()来找xml的版本和命名空间。(version=8.0是?)%XML.Documnet是DOM方式的存放,查找xml。 

还有一个是%XML.XPATH.Document,用xpath查找节点内容比较方便。 

%XML.XPATH.Document 前提是我知道要取值的确切位置可以,实际情况是 不清楚结构。%XML.Document 创建对象的时候  因为xml里面有xsd路径 失败了。这个值是未知的。

你是要遍历XML DOM树?可以如下使用:

ClassMethod Test()
{
    Set x="<?xml version=""1.0"" ?><root xmlns=""test"" xmlns:mc=""test1"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""test2""><!--this is a test--><id code=""test3""/></root>"

    try
    {

    $$$ThrowOnError(##class(%XML.XPATH.Document).CreateFromString(x, .doc))
    Set doc.PrefixMappings="s test"
    $$$ThrowOnError(doc.EvaluateExpression("/s:root", ".", .field))
    #dim obj As %XML.XPATH.DOMResult = field.GetAt(1)
    
    while obj.Read() 
    {
      if obj.HasValue 
      {
        write obj.Path,": ",obj.Value,!
      }
      if obj.HasAttributes
      {
          for i=1:1:obj.AttributeCount
          {
            d obj.MoveToAttributeIndex(i)
            w obj.Name,":",obj.Value,!
          }
      }
    }
    
  }catch(ex)
  {
    write "Error ", ex.DisplayString(),!
  }
}

输出:
xmlns:xml:http://www.w3.org/XML/1998/namespace
xmlns:test
xmlns:mc:test1
xmlns:xsi:http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation:test2
root\: this is a test
code:test3