.net 按属性值选择XML节点
我有一个点变量,我需要选择节点及其坐标,然后更改属性值。我想做一些类似的事情:.net 按属性值选择XML节点,.net,xml,f#,.net,Xml,F#,我有一个点变量,我需要选择节点及其坐标,然后更改属性值。我想做一些类似的事情: let node=xmld.SelectSingleNode(“/location/hotspot[@X='542'@Y='452']”) node.Attributes[0].Value我个人会使用LINQ到XML: <location> <hotspot name="name1" X="444" Y="518" /> <hotspot name="name2" X="542"
let node=xmld.SelectSingleNode(“/location/hotspot[@X='542'@Y='452']”)
node.Attributes[0].Value我个人会使用LINQ到XML:
<location>
<hotspot name="name1" X="444" Y="518" />
<hotspot name="name2" X="542" Y="452" />
<hotspot name="name3" X="356" Y="15" />
</location>
请注意,如果可能没有任何匹配元素,则应使用SingleOrDefault
;如果可能有多个匹配元素,则应使用First
/FirstOrDefault
找到正确的热点
节点后,可以轻松设置属性:
var doc = XDocument.Load(...);
var node = doc.Root
.Elements("hotspot")
.Single(h => (int) h.Attribute("X") == x &&
(int) h.Attribute("Y") == y);
不能使用XPath表达式一次填充多个变量。XPath表达式返回的唯一值(或者在更技术的层面上,由计算XPath表达式的SelectSingleNode
返回的值)是表达式标识的Xml节点
一旦将
元素作为节点对象,就必须使用DOM API来读取和写入属性值,或者可能使用一些实用程序来自动将属性值传输到强类型数据对象,或者从强类型数据对象传输属性值。也许类似的方法可以工作:
//尝试查找与指定点对应的元素
让tryFindElementByPoint(xmlDoc:XmlDocument)指向=
let pointElement=
指向
||>sprintf“/位置/热点[@X='%u'@Y='%u']
|>xmlDoc.SelectSingleNode
将pointElement与
|空->无
|x->一些x
//查找与指定点对应的元素,然后更新该元素的属性值。
让UpdatePoint元素xmlDoc指向(newValue:string)=
将TryFindlementByPoint xmlDoc点与
|无->
点| |>failwithf“找不到点(%u,%u)的XML元素。”
|某些节点->
//TODO:确保更新了正确的属性!
node.Attributes.[0].Value试试这个
node.SetAttributeValue("X", newX);
node.SetAttributeValue("Y", newY);
这真的很容易。假设我要修改节点中的第一个属性:
//let node = xmld.SelectSingleNode("/location/hotspot[@X='542' and @Y='452']")
let query = sprintf "/location/hotspot[@X='%d' and @Y='%d']"
let node = xmld.SelectSingleNode(query 542 452)
let node=xmld.SelectSingleNode(“/location/hotspot[@X='”+string(current.X)+“][@Y='”+string(current.Y)+“]”)
node.Attributes。[0].Value是否可以循环使用,比较属性,然后更改正确的属性?要为XML文件创建强类型类,应将XML反序列化为对象。查看xsd实用程序以生成基本代码。否则……只需实现一个自定义读取器,您的代码将使用该读取器,它将只获得结构(而不是原始XML)。@FrankLioty:是的,不仅仅是XML。
let node = xmld.SelectSingleNode("/location/hotspot[@X='" + string(current.X) + "'] [@Y='" + string(current.Y) + "']")
node.Attributes.[0].Value <- v