How to insert a child node with specific index in Karate
您好,我正在尝试将一些节点插入到 xml 文件中
举个假例子
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<Family>
<Father> <Name>abc</Name> <Age>4</Age> <Gender>Male</Gender> </Father> <Mother> <Name>bcd</Name> <Age>5</Age> <Gender>Female</Gender> </Mother> <Child> <Name>bcd</Name> <Age>5</Age> <Gender>Female</Gender> <Toy> <Brand>def</Brand> <Price>20</Price> <Size>Middle</Size> </Toy> </Child> </Family> |
我可以在价格节点之后添加一个节点吗?
或者是否有任何子节点重复多次?
我已经尝试删除父 \\’Toy\\’ 节点并使用 * set 来重建它。但它似乎会将部分插入到子节点的第一位,而不是在性别节点之后
1
2 3 4 5 6 7 8 9 10 |
* remove Family/Child/Toy
* set Family/Child/Toy = “”“ <Toy> <Brand>def</Brand> <Price>20</Price> <Price>20</Price> <Size>Middle</Size> </Toy> ““” |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<Family>
<Father> <Name>abc</Name> <Age>4</Age> <Gender>Male</Gender> </Father> <Mother> <Name>bcd</Name> <Age>5</Age> <Gender>Female</Gender> </Mother> <Child> <Toy> <Brand>def</Brand> <Price>20</Price> <Price>20</Price> <Size>Middle</Size> </Toy> <Name>bcd</Name> <Age>5</Age> <Gender>Female</Gender> </Child> </Family> |
所以我目前的解决方案是删除整个家庭部分并用整个身体的一部分替换它,以确保所有内容都按正确的顺序放置。
请问有没有更简单的解决方法?
非常感谢
根据 Peter 的回答,您需要使用 replace 在元素 ‘a’ 之间插入
- 谢谢蒂姆,这正是我正在寻找的:D
是的,操作 XML 并不容易。也许字符串 replace 可以解决问题。请注意,您可以使用带有括号表示法的 XPath 来处理重复/嵌套元素:
1
2 3 4 5 6 7 8 9 10 11 |
* def foo =
“”“ <root> <first>1</first> <second>2</second> </root> ““” * replace foo.<second>2</second> = ‘<second>2</second><thirds><third>3.1</third></thirds>’ * xml foo = foo * set foo /root/thirds/third[2] = ‘3.2’ * print foo |
导致:
1
2 3 4 5 6 7 8 |
<root>
<first>1</first> <second>2</second> <thirds> <third>3.1</third> <third>3.2</third> </thirds> </root> |
- 感谢您回答问题!但我还是有点迷茫。如果我试图进入更深层次,更改 <second> 节点中的一个子节点(<second><c></c></second>),我该如何使用替换来管理这?
- 嗨彼得,你能看看我在下面添加的答案吗?谢谢:)
- @Jackson 不,您不能”在之间插入节点”,因此请使用 replace 或覆盖整个”父”节点。 XML 中的重复节点可以在 XPath 中完成,如上所示。
对不起,彼得,我必须创建另一个答案来格式化内容
我已经尝试过您提供的示例,它确实有效。但我的情况更像
1
2 3 4 5 6 7 8 9 10 |
<root>
<first>1</first> <second>2</second> <thirds> a <third>3.1</third> b </thirds> <fourth>4</fourth> </root> |
我正在尝试在”a”和”b”节点之间添加另一个节点
如果我按照你的建议添加了一个节点
1
2 |
* set foo /root/thirds/third[2] = ‘3.2’
* set foo /root/thirds/third[3] = ‘3.2’ |
那么第二个节点会出现在其父节点的底部
1
2 3 4 5 6 7 8 9 10 11 12 |
<root>
<first>1</first> <second>2</second> <thirds> a <third>3.1</third> b <third>3.2</third> <third>3.2</third> </thirds> <fourth>4</fourth> </root> |
所以如果我需要连续多次复制节点,或者在’a’和’b’节点之间插入,是否可以?
来源:https://www.codenong.com/59060496/