[英]Xml file with C# can't get the value
這是我的xml文件
<?xml version="1.0" encoding="ASCII"?>
<Vitals>
<Vendor>General Electric Healthcare</Vendor>
<Model>Pro/Procare</Model>
<Result name="Mean_arterial_pressure">
<Value>86</Value>
<Units name="mmHg"></Units>
<Time_stamp year="2008" month="11" day="18" hour="12" minute="33" second="14"></Time_stamp>
</Result>
<Result name="Systolic_blood_pressure">
<Value>130</Value>
<Units name="mmHg"></Units>
<Time_stamp year="2008" month="11" day="18" hour="12" minute="33" second="14"></Time_stamp>
</Result>
<Result name="Diastolic_blood_pressure">
<Value>67</Value>
<Units name="mmHg"></Units>
<Time_stamp year="2008" month="11" day="18" hour="12" minute="33" second="14"></Time_stamp>
</Result>
<Result name="Pulse">
<Value>73</Value>
<Units name="BPM"></Units>
<Method>blood_pressure</Method>
<Time_stamp year="2008" month="11" day="18" hour="12" minute="33" second="14"></Time_stamp>
</Result>
</Vitals>
這是我的源代碼,我遇到了如何獲取結果名稱和值的問題?
private void btnReadXml_Click(object sender, EventArgs e)
{
Hashtable h = new Hashtable();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("C:\\dinamap.xml");
XmlNodeList doc_results = xmlDoc.GetElementsByTagName("Vitals/Vendor/Model/Result[@name='Systolic_blood_pressure']");
foreach (XmlNode pnode in doc_results)
{
foreach (XmlNode cnode in pnode.ChildNodes)
{
if (cnode.Name == "Value")
{
h.Add(pnode.Attributes["name"].InnerText + cnode.Name, cnode.Attributes["name"].InnerText);
}
else
{
h.Add(pnode.Attributes["name"].InnerText + "_" + cnode.Name, cnode.InnerText);
}
}
}
}
我可以知道我的代碼有什么問題嗎? 總是無法獲得價值。
我需要從xml文件中獲取值。
在第5行,您的xPath指定Model
是Vendor
的子級,而Vendor
僅包含一個字符串( <Vendor>General Electric Healthcare</Vendor>
)。
此外,要使用xPath導航,我建議您使用SelectNodes
函數。
試試這個代替:
XmlNodeList doc_results = xmlDoc.SelectNodes("/Vitals/Model/Result[@name='Systolic_blood_pressure']");
您當前正在嘗試檢索子節點的“名稱” attribute
,在您的值節點的情況下,該attribute
實際上沒有。 如果使用cnode.Value
,則可以獲取文本注釋的內容。
另外, Result
不是 Model
的子代,而Model
不是 Vendor
的子代。 您可能想要適當地讓他們成為孩子,或者更改您為doc_results
設置的路徑
如果您使用LINQ to XML會更容易。
var doc = XDocument.Load("path/to/xml");
var results =
from result in doc.Descendants("Result")
select new
{
Name = (string) result.Attribute("name"),
Value = (string) result.Element("Value"),
Units = (string) result.Element("Units").Attribute("name")
};
然后,如果需要,可以按名稱過濾:
var sysBp = results.Single(x => x.Name == "Systolic_blood_pressure");
請參閱此小提琴以獲得有效的演示。
private void btnReadXml_Click(object sender, EventArgs e) { var doc = XDocument.Load("C:\\\\dinamap.xml"); var results = from result in doc.Descendants("Result") select new { Name = (string)result.Attribute("name"), Value = (string)result.Element("Value"), Units = (string)result.Element("Units").Attribute("name") }; foreach (var result in results) { MessageBox.Show("{result.Name}: {result.Value} {result.Units}"); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.