C#打开XML并获取值
本文关键字:获取 XML 打开 | 更新日期: 2023-09-27 17:51:01
我正在打开一个XML文件,需要从中获取一个特定的值。我向recordingowner读取,然后我想获取它的值。
这就是我到目前为止所想到的,其中n是xml文件的路径
public void ReadXMLFile(string n)
{
if (Path.GetExtension(n) == ".xml")
{
// XML File found
XmlDocument doc = new XmlDocument();
doc.Load(n);
string xmlcontents = doc.InnerXml;
using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents)))
{
reader.ReadToFollowing("recordingowner");
string t = reader.Value;
Console.WriteLine(t);
}
}
}
然而,t不包含任何内容。这是XML文件
<recording>
<dataformat>audio</dataformat>
<starttime>2014-03-19 11:52:42:000 +0100</starttime>
<endtime>2014-03-19 11:58:15:000 +0100</endtime>
<nostart>false</nostart>
<noend>false</noend>
<recordingtype>stnbulk</recordingtype>
<recordingline/>
<servicename>1000</servicename>
<servicenumber/>
<deliberatebreak>0</deliberatebreak>
<calldirection>Incoming</calldirection>
<filename>66633769853.wav</filename>
<otherinum>0</otherinum>
<callparty>1</callparty>
<recordingowners>
<recordingowner>411111111</recordingowner>
</recordingowners>
<parties>
<party id="1">
<number>0000</number>
<pstarttime>2014-03-19 11:58:15:982 +0100</pstarttime>
<pendtime>2014-03-19 11:58:15:982 +0100</pendtime>
</recording>
欢迎任何帮助!
1( 您提供的XML无效,因为它缺少参与方和参与方的两个结束标记
2( 使用以下内容替换字符串t=读取器。价值具有string t=读取器。ReadElementString((;
// XML File found
XmlDocument doc = new XmlDocument();
doc.LoadXml(val);
string xmlcontents = doc.InnerXml;
using (XmlReader reader = XmlReader.Create(new StringReader(xmlcontents)))
{
reader.ReadToFollowing("recordingowner");
string t = reader.ReadElementString();
Console.WriteLine(t);
}
reader.ReadElementContentAsString();
修复
我可能会这样做(但它确实需要是有效的XML(
var t = XDocument.Load(n)
.Element("recording")
.Elements("recordingowners")
.First()
.Element("recordingowner")
.Value