怎么给xml节点添加属性

bryant_wyf 2010-10-11 11:42:28
小弟请教各位大虾
有一个xml: <root><row><item1>1</item1><item2>2</item2></row><row><item1>3</item1><item2>4</item2></row></root>。
row节点的个数不定,我想给所有item1节点添加一个属性align="right"。
请问怎么实现。

SET @myDoc.modify('insert attribute align {"right"} into (/root/row/item1)[1]')
小弟只知道这种方法加属性,可是这种方法永远都只能给确定的某个节点加。实现不了我要的结果。
...全文
275 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
bryant_wyf 2010-10-14
  • 打赏
  • 举报
回复
呵呵,自己想出个方法来。

declare @xml xml
set @xml = '<root><row><item1>1</item1><item2>2</item2></row><row><item1>3</item1><item2>4</item2></row></root>'
declare @temp xml = ''
set @temp =
(
select
'right' 'item1/@aligh'
, isnull(A.item1,'') as item1
, isnull(A.item2,'') as item2
from
(
select
A.value('(item1/text())[1]', 'VARCHAR(MAX)') AS item1
, A.value('(item2/text())[1]', 'VARCHAR(MAX)') AS item2
FROM @xml.nodes('/root/row') AS R(A)
) A
For Xml Path('row')
)
declare @xml2 xml = '<root />'
SET @xml2.modify( 'insert sql:variable("@temp") into (/root)[1]')
select @xml2


这个@xml2就是我想要的结果。
SQLCenter 2010-10-11
  • 打赏
  • 举报
回复
好像是无解
liangCK 2010-10-11
  • 打赏
  • 举报
回复
xquery赋值给一个新的变量.
bryant_wyf 2010-10-11
  • 打赏
  • 举报
回复
补充一点。我是想在存储过程中实现的。
missfeng 2010-10-11
  • 打赏
  • 举报
回复

NodeList nodeList = doc.getElementsByTagName("items");

for (int i = 0; i < nodeList.getLength(); i++) {
Element e= (Element) nodeList.item(i);
NamedNodeMap attributes = e.getAttributes();//获取属性
for (int j = 0; j < attributes.getLength(); j++) {
Attr attr = (Attr) attributes.item(j);
System.out.println(attr.getValue());
属性值获取出来再做修改试一下
}
bryant_wyf 2010-10-11
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 liangck 的回复:]

xquery赋值给一个新的变量.
[/Quote]

能详细说明一下吗?谢谢。

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧