[英]XML get value of tag without childrens value
我正在嘗試獲取下面的<data>
標簽的值(這是一個測試值)。 我在Windows窗體應用程序中使用XElement進行了閱讀。 但是,如果我使用element.Value
我也會得到一個包含所有子代值的字符串。 需要讀取的最終XML文件是生成的XML文件。 因此,解決方案需要動態。 無固定名稱。
element.Value
的結果是: This is a test value Jack22New YorkGuido21HollywoodMichael20BostonMy-Computer-1
XML檔案:
<?xml version="1.0" encoding="UTF-8"?>
<data name="data_resource" howabout="no">
This is a test value
<persons>
<person>
<name>Jack</name>
<age>22</age>
<pob>New York</pob>
</person>
<person>
<name>Guido</name>
<age>21</age>
<pob>Hollywood</pob>
</person>
<person>
<name surname="Bats">Michael</name>
<age>20</age>
<pob>Boston</pob>
</person>
</persons>
<computers>
<computer>
<name>My-Computer-1</name>
<test>
<test2>
<test3>
<test4 testAttr="This is an attribute" y="68" x="132">
Hatseflatsen!
</test4>
</test3>
</test2>
</test>
</computer>
</computers>
</data>
有沒有人為此提供解決方案或解決方案,使我僅獲得其自身標簽的價值,而不是他們所有孩子的價值?
這將立即獲取元素內的所有文本,而不獲取其后代的文本:
var textValues = element.Nodes()
.Where(n => n.NodeType == XmlNodeType.Text)
.Select(n => n.ToString().Trim());
string value = string.Join("", textValues); // value is: This is a test value
使用xpath:
XmlDocument doc = new XmlDocument();
doc.Load(/*The path to your xml*/);
XmlNode root = doc.DocumentElement;
XmlNode node = root.SelectSingleNode("/data");
var v = node.FirstChild; //This contains "This is a test value"
使用Linq2Xml,嘗試以下操作:
string xmlString = //read your XML or load the file using XDocument.Load();
XDocument doc = XDocument.Parse(xmlString);
System.Console.WriteLine(doc.Root.FirstNode);
在每種情況下,都可以通過將doc.Root
替換為目標XElement
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.