Skip to main content
 首页 » 编程设计

c#之如何在 C# 中获取节点文本值的父级

2024年02月20日12cyq1162

我有以下 xml:

<?xml version="1.0"?> 
<catalog> 
   <book id="bk101"> 
      <author>Gambardella, Matthew</author> 
      <title>XML Developer's Guide</title> 
      <genre>Computer</genre> 
      <price>44.95</price> 
      <publish_date>2000-10-01</publish_date> 
      <description>An in-depth look at 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 battles corporate zombies,  
      an evil sorceress, and her own childhood to become queen  
      of the world.</description> 
   </book> 
</catalog> 

我找到了名为“Midnight Rain”的标题。现在我想知道谁是他的 parent ,以便我可以使用 <author>文本节点。我试过类似的东西:

  var xpath = "../*[local-name() != 'title']"; 
       xml.Load(xmlalltext); 
       var xl1 = xml.SelectNodes(xpath); 
       MessageBox.Show(xl1.Item(0).InnerText.ToString()); 

请您参考如下方法:

如果已经找到title节点,要查找父节点,则直接选择当前节点的父节点即可。

var parentNode = titleNode.SelectSingleNode(".."); 

如果您正在寻找作者节点:

var authorNode = titleNode.SelectSingleNode("../author"); 

或者,您可以查找前面或后面的 sibling :

var authorNode = titleNode.SelectSingleNode("following-sibling::author") ?? titleNode.SelectSingleNode("preceding-sibling::author"); 

编辑:要回答您的评论,如果您只有标题的字符串,那么您可以使用以下内容来获取作者:

string xml = @"xml..."; 
var doc = XDocument.Parse(xml); 
string author = doc 
    .Descendants("book") 
    .Where(x => x.Element("title").Value == "Midnight Rain") 
    .Select(x => x.Element("author").Value) 
    .FirstOrDefault();