[英]Get a xml element with specific attribute value in c#
我需要獲取SubTopic元素的值,該元素具有名為“ Name”的特定值的attribute
。 我這樣做
IEnumerable<XElement> list =
(from el in xdoc.Elements()
where (string)el.Attribute("Name") == "creatingTests"
select el);
集合具有零個元素。
我嘗試將xdoc.Elements("SubTopic")
代替空參數,但沒有成功。
我的XML文件結構;
<?xml version="1.0" encoding="windows-1250" ?>
<Help Title="TestTool - tematy pomocy">
<Topic Name="creatingTests" Title="Tworzenie testów">
<SubTopic Name="saveload" Title="Zapis i odczyt z pliku">
Content
</SubTopic>
</Topic>
</Help>
如何獲得Help / Topic(Name =“ creatingTests”)的值?
xdoc
當然是帶有已加載xml的XDocument
對象,它確實具有文件的內容。
xdoc.Elements()
僅返回一個元素xdoc.Elements()
樹的根(在您的示例中為<Help>
元素)。
將查詢更改為:
IEnumerable<XElement> list =
(from el in xdoc.Root.Elements()
where (string)el.Attribute("Name") == "creatingTests"
select el);
它返回一個元素的collection。 使用First
或FirstOrDefault
將其作為單個項目而不是集合來獲取:
XElement item = (from el in xdoc.Root.Elements()
where (string)el.Attribute("Name") == "creatingTests"
select el).FirstOrDefault();
這是使用System.Xml.XPath的替代方法:
using System.Xml.Linq;
using System.Xml.XPath;
class Program
{
static void Main(string[] args)
{
var xdoc = XDocument.Load("input.xml");
var subTopic = xdoc
.XPathSelectElement("//Topic[@Name='creatingTests']/SubTopic");
}
}
非常簡單的方法是使用XSLT。
1.創建一個XSLT模板。
2.在c#中調用它。
xmlDaynamic.DocumentContent = "Your XML Input";
xmlDaynamic.TransformSource = "YourTemplate with extension";
3.您的任務完成了。
4.xmlDaynamic是一個服務器控件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.