簡體   English   中英

如何使用c#從節點內部獲取字符串的一部分

[英]How to get part of a string from inside a node using c#

我有一個像xml這樣的文件

<?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從每個節點<description>提取值“[(\\ d +) - ([az])]”並將其存儲在變量中,或者可以使用它將這些提取的值添加到新的屬性各個節點如<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");

我不熟悉linq2xml,所以我使用XmlDocument和XPath表達式來查找我感興趣的節點。這樣的事情:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);

var books = doc.SelectNodes("//catalog/book");
foreach (XmlNode book in books)
{
     var description = book.SelectSingleNode("description");
     Regex regex = new Regex(@"(\[.*\])");
     var match = regex.Match(description.InnerText);
     if (match.Success)
     {
          var val = match.Groups[0].Value;
          var attribute = doc.CreateAttribute("val");
          attribute.Value = val;
          description.Attributes.SetNamedItem(attribute);
     }
}

// Convert XmlDocument back to string
var stringWriter = new StringWriter();
var xmlTextWriter = XmlWriter.Create(stringWriter);
doc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
xmlString = stringWriter.GetStringBuilder().ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM