[英]How to check if element exists in this xml c#
我有編程這個問題。 對於每個特定的端口元素,我要檢查<script>
是否存在。 <script>
是<port>
節點元素的子元素。 以這個例子為例,這是圖像的鏈接:
http://i.stack.imgur.com/T2FGr.png
// Leggi il file xml
XDocument xml = XDocument.Load(pathFile.Text);
var hosts = from h in xml.Descendants("address")
select new
{
addr = h.Attribute("addr").Value,
addrtype = h.Attribute("addrtype").Value
};
foreach (var host in hosts)
{
if (host.addrtype == "ipv4")
{
console.Text += host.addr + Environment.NewLine;
console.Text += host.addrtype + Environment.NewLine;
var ports = xml.Descendants("port");
foreach (var port in ports)
{
var script = port.Element("script");
var hasScriptElement = script != null;
?? -> how can i get the elem pem key value? thanks!!
}
}
}
使用XDocument
...
var ports = document.Descendants("port");
foreach (var port in ports) {
var script = port.Element("script");
if (script != null)
{
var pem = script.Descendants("elem")
.FirstOrDefault(n => n.Attribute("pem") != null);
}
}
通用答案:
<port
,然后>
</port>
<script
,則您有腳本 這是一個控制台應用程序,演示了如何完成此操作:
class Program
{
static void Main(string[] args)
{
string fileName = "c:\path\to\file\test.xml";
var xmlDoc = new XmlDocument();
xmlDoc.Load(File.OpenRead(fileName));
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("port");
XmlNodeReader nodeReader;
foreach (var node in nodeList)
{
using(nodeReader = new XmlNodeReader((XmlNode)node))
{
if(nodeReader.ReadToDescendant("script"))
{
Console.WriteLine("Found script tag");
}
}
}
Console.ReadKey();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.