gpt4 book ai didi

java - 从 Yang 模型生成 xml/json

转载 作者:数据小太阳 更新时间:2023-10-29 02:39:22 27 4
gpt4 key购买 nike

我一直在努力寻找可以从 java 中的 yang 模型生成示例 xml/json 数据的东西,例如对于 xsd,有一些工具可以生成示例 xml。

我试过 Pyang:1. 它在 Python 中。2. 转换后它给了我 yin 格式,它是 xml 等同于 yang 规范。对于例如。如果我使用 pyang 将其转换为 YIN,则遵循 yang 代码:

 leaf templateSendPeriod {
when "../exportProtocol!='netflow-v5'";
type uint16;
default 60;
units seconds;
}

这是我得到的-

 <leaf name="templateSendPeriod">
<when condition="../exportProtocol!='netflow-v5'"/>
<type name="uint16"/>
<default value="60"/>
<units name="seconds"/>
</leaf>

我想要的是

<templateSendPeriod></templateSendPeriod>

这样我就可以获得 xml,输入详细信息并根据相同的 yang 进行验证。

最佳答案

你可以这样做,首先声明你的模型

// module name
module napalm-star-wars {

// boilerplate
yang-version "1";
namespace "https://napalm-yang.readthedocs.io/napalm-star-wars";

prefix "napalm-star-wars";

// identity to unequivocally identify the faction an individual belongs to
identity AFFILIATION {
description "To which group someone belongs to";
}

identity EMPIRE {
base AFFILIATION;
description "Affiliated to the empire";
}

identity REBEL_ALLIANCE {
base AFFILIATION;
description "Affiliated to the rebel alliance";
}

// new type to enforce correctness of the data
typedef age {
type uint16 {
range 1..2000;
}
}

// this grouping will all the personal data we will assign to individuals
grouping personal-data {
leaf name {
type string;
}
leaf age {
type age;
}
leaf affiliation {
type identityref {
base napalm-star-wars:AFFILIATION;
}
}
}

// this is the root object defined by the model
container universe {
list individual {
// identify each individual by using the name as key
key "name";

// each individual will have the elements defined in the grouping
uses personal-data;
}
}
}

用树表示你的模型

$ pyang -f tree napalm-star-wars.yang
module: napalm-star-wars
+--rw roster
+--rw individual* [name]
+--rw name string
+--rw age? age
+--rw affiliation? identityref

稍后在您的 python 代码中使用它:

>>> import napalm_star_wars
>>>
>>> sw = napalm_star_wars.napalm_star_wars()
>>>
>>> obi = sw.universe.individual.add("Obi-Wan Kenobi")
>>> obi.affiliation = "REBEL_ALLIANCE"
>>> obi.age = 57
>>>
>>> luke = sw.universe.individual.add("Luke Skywalker")
>>> luke.affiliation = "REBEL_ALLIANCE"
>>> luke.age = 19

在这里,您可以根据自己的选择获得获取 json 或 xml 的答案。

import json
>>> print(json.dumps(sw.get(), indent=4))

关于java - 从 Yang 模型生成 xml/json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com