[英]ChildNodes based on Parent xml Attribute in C#
這是我的Xml。
<SCat>
<S SId="1" SName="M" FName="MA">
<Cat>
<C CId="2" CName="CAS" FName="c-a" />
<C CId="3" CName="DAC" FName="d-a" />
</Cat>
</S>
<S SId="2" SName="I" FName="IA">
<Cat>
<C CId="2" CName="CAS" FName="c-a" />
<C CId="3" CName="DAC" FName="d-a" />
</Cat>
</S>
<S SId="3" SName="D" FName="DA">
<Cat>
<C CId="2" CName="CAS" FName="c-a" />
<C CId="3" CName="DAC" FName="d-a" />
</Cat>
</S>
</SCat>
我寫了這段代碼。
int Scode = 1;
dsS = new DataSet();
dsS.ReadXml(HttpContext.Current.Server.MapPath(Path));
這就是我卡住的地方。 我想在具有屬性“ SId” = 1的數據表中獲取所有“貓”。
謝謝
使用下面的XPATH,您將獲得SId ='1'
所有子節點
/SCat/S[@SId='1']/Cat
您應該使用XmlDocument對象加載整個文檔,然后提供節點路徑和屬性選擇器。 所有這些都在MSDN( link1 )上有詳細記錄。 以下是該站點的代碼片段:
清單1。
using System;
using System.IO;
using System.Xml;
public class Sample {
public static void Main() {
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book xmlns:bk='urn:samples' bk:ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
XmlNode root = doc.FirstChild;
//Create a new attribute.
string ns = root.GetNamespaceOfPrefix("bk");
XmlNode attr = doc.CreateNode(XmlNodeType.Attribute, "genre", ns);
attr.Value = "novel";
//Add the attribute to the document.
root.Attributes.SetNamedItem(attr);
Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out);
}
}
清單2( link2 )
XElement root = XElement.Load("PurchaseOrder.xml");
IEnumerable<XElement> address =
from el in root.Elements("Address")
where (string)el.Attribute("Type") == "Billing"
select el;
foreach (XElement el in address)
Console.WriteLine(el);
希望這會有所幫助。 問候,AB
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.