[英]How can i get the parent of node text value in c#?
我有以下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>
我找到了名為“午夜雨”的標題。 現在我想知道誰是他的父母,以便我可以使用<author>
文本節點。 我嘗試過類似的東西:
var xpath = "../*[local-name() != 'title']";
xml.Load(xmlalltext);
var xl1 = xml.SelectNodes(xpath);
MessageBox.Show(xl1.Item(0).InnerText.ToString());
如果您已找到標題節點並且正在查找父節點,則只需選擇當前節點的父節點即可。
var parentNode = titleNode.SelectSingleNode("..");
如果您正在尋找作者節點:
var authorNode = titleNode.SelectSingleNode("../author");
或者,您可以尋找前面或后面的兄弟姐妹:
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();
使用XLinq
sample.xml(在下面的snipped中)包含xml數據
XElement root = XElement.Parse(File.ReadAllText("sample.xml"));
var matchingBooks = root.Descendants().Where(i=>String.Equals(i.Value,"Midnight Rain")).Select(i=>i.Parent) ;
var authors = matchingBooks.Elements("author");
LinqPad輸出
matchingBooks.Dump();
authors.Dump();
<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>
<author>Ralls, Kim</author>
您可以使用此xpath expession來獲取作者節點
"/catalog/book[title='Midnight Rain']/author"
或者這個來獲取父節點
"/catalog/book[title='Midnight Rain']"
例如。
var result = xml.SelectNodes(string.Format("/catalog/book[title='{0}']/author", "Midnight Rain"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.