如何将Sysrepo、NETCONF的XPath解析为指定JSON格式?
解析Sysrepo回调中的YANG XPath为指定JSON结构的方法
针对你遇到的这种带YANG模块前缀和列表键过滤的XPath解析需求,没有现成库直接输出目标JSON结构的话,可以通过自定义字符串解析逻辑或者结合YANG模型元数据解析两种方式实现,以下是具体方案:
一、自定义字符串解析逻辑(快速实现)
这类XPath有固定结构规律,可通过正则表达式+字符串拆分逐步提取关键信息,步骤如下:
1. 拆分XPath层级节点
将XPath按/分割,剔除开头的空字符串(因XPath以/起始),得到节点数组。比如第一个示例拆分后为:["ietf-interfaces:interfaces", "interface[name='mgmt7']", "ietf-ip:ipv4", "mtu"]
2. 提取顶层模块与基础路径
处理第一个节点ietf-interfaces:interfaces,按:分割得到模块名(对应JSON的class)ietf-interfaces和起始路径interfaces。
3. 识别列表节点并提取item值
遍历后续节点,定位带[key='value']格式的列表节点:
- 对
interface[name='mgmt7'],用正则(.+)\[(.+?)='(.+?)'\]匹配,提取节点名interface、item值mgmt7,将前面的interfaces与该节点名拼接为JSON的path:interfaces/interface。
4. 处理子树模块与路径
剩余节点ietf-ip:ipv4和mtu:
- 拆分
ietf-ip:ipv4得到子模块ietf-ip,将ipv4与mtu拼接为子路径ipv4/mtu,组成subtree结构。
示例代码片段(Python)
import re def parse_yang_xpath(xpath): nodes = [n for n in xpath.split('/') if n] result = {} # 处理顶层模块和起始路径 top_node = nodes[0] top_class, top_path = top_node.split(':') result['class'] = top_class current_path = top_path # 遍历识别列表节点 item = None subtree_start_idx = 0 for idx, node in enumerate(nodes[1:], 1): if '[' in node and ']' in node: match = re.match(r'(.+)\[(.+?)=\'(.+?)\'\]', node) if match: node_name, _, item_val = match.groups() current_path += f'/{node_name}' item = item_val subtree_start_idx = idx + 1 break else: current_path += f'/{node}' result['path'] = current_path if item: result['item'] = item # 组装子树结构 if subtree_start_idx < len(nodes): subtree_nodes = nodes[subtree_start_idx:] subtree_first = subtree_nodes[0] if ':' in subtree_first: sub_class, sub_path_part = subtree_first.split(':') sub_path = sub_path_part else: sub_class = result['class'] sub_path = subtree_first for node in subtree_nodes[1:]: sub_path += f'/{node}' result['subtree'] = { 'class': sub_class, 'path': sub_path } return result # 测试第一个示例 xpath1 = "/ietf-interfaces:interfaces/interface[name='mgmt7']/ietf-ip:ipv4/mtu" print(parse_yang_xpath(xpath1))
运行后将输出目标JSON结构。
二、结合YANG模型元数据解析(更严谨)
若需要处理多键列表、嵌套列表等复杂XPath场景,可借助Sysrepo依赖的libyang库,结合YANG模型元数据解析:
- 将对应的YANG模块(如ietf-interfaces、ietf-ip)加载到libyang上下文。
- 使用libyang的
lyxp_parse等函数解析XPath,生成抽象语法树(AST)。 - 遍历AST节点,提取模块名、节点路径、列表键值等信息,组装为目标JSON结构。
这种方式能精准处理各类复杂场景,比如第二个示例的address[ip='192.168.1.15']、第三个示例的多键列表control-plane-protocol[type='ietf-routing:static'][name='static']。
注意事项
- 自定义解析逻辑适合简单场景,若XPath包含复杂过滤条件或嵌套结构,优先选择libyang辅助解析。
- 处理时需注意XPath可能省略默认模块前缀的情况,需结合Sysrepo的模块上下文补全。
内容的提问来源于stack exchange,提问作者Xuo Guoto
相关产品推荐
相关产品推荐

