我有一个像
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide [49-o]</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at [41-p] creating applications with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect [100-x] battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology society in England, the [01-i] young survivors lay the foundation for a new society.</description>
</book>
</catalog>
如何使用linq2xml从每个节点中提取值“ [(\ d +)-([az])]”<description>
并将其存储在变量中,或者像将这些提取值添加到各个节点的新属性中一样使用它喜欢<description val="41-p">
等?
你可以用 Descendants
Regex regex = new Regex(@"(\d+)-([a-z])");
var xdoc = XDocument.Parse(xml);
var descriptions = xdoc.Descendants("description")
.Where(x => regex.Match(x.Value).Success)
.Select(x => regex.Match(x.Value).Value).ToList();
Output:
41-p
100-x
01-i
如果要将提取的值设置为属性;
Regex regex = new Regex(@"(\d+)-([a-z])");
var xdoc = XDocument.Parse(xml);
var descriptions = xdoc.Descendants("description")
.Where(x => regex.Match(x.Value).Success);
foreach (var description in descriptions)
{
var regexResult = regex.Match(description.Value).Value;
var attribute = new XAttribute("id", regexResult);
description.Add(attribute);
}
xdoc.Save("sample.xml");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句