[英]Load XML in C# InnerText
I have a C# service where I loop every 1 seconds trough a directory looking for XML files. 我有一个C#服务,我每隔1秒钟循环通过一个目录以查找XML文件。
These XML files may look like this: 这些XML文件可能如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<job>
<type>freelance</type>
<text>blah</text>
</job>
In a foreach I do the following: 在foreach中,我执行以下操作:
var doc = new XmlDocument();
doc.LoadXml(xmlFile);
XmlNode xmltype = doc.DocumentElement.SelectSingleNode("/job/type");
And than I would like to use these strings to use in my program, however. 而且,我想在程序中使用这些字符串。 Using
xmltype.InnerText
does not work. 使用
xmltype.InnerText
不起作用。 Documentation on MSDN does not provide me with anything new and I would like to know what I am doing wrong. MSDN上的文档没有为我提供任何新内容,我想知道我做错了什么。
This following console program will output "freelance". 下面的控制台程序将输出“ freelance”。 I think the issue may be with some of your XML - do all of your XML docs follow the same schema?
我认为问题可能出在您的某些XML上-您所有的XML文档都遵循相同的模式吗? I am guessing that the code fails with a
NullReferenceException
at some point. 我猜测代码有时会失败并显示
NullReferenceException
。 I've added a null check to protect against this possible scenario. 我添加了一个空检查,以防止出现这种情况。
To help debug your service I tend to use the technique described here to run the app as console application (for easy debugging) or windows service. 为了帮助调试服务,我倾向于使用此处介绍的技术将应用程序作为控制台应用程序(以便于调试)或Windows服务运行。
using System;
using System.Xml;
public class Program
{
static string xmlFile = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<job>
<type>freelance</type>
<text>blah</text>
</job>";
public static void Main()
{
var doc = new XmlDocument();
doc.LoadXml(xmlFile);
XmlNode xmltype = doc.DocumentElement.SelectSingleNode("/job/type");
if(xmltype==null)
{
Console.WriteLine("/job/type not found");
} else {
Console.WriteLine(xmltype.InnerText);
}
}
}
First you have to check the xml file.whether is there any data or not. 首先,您必须检查xml文件。是否有数据。 after that take the one particular node check for
innerText
. 之后,采取一个特定的节点检查
innerText
。 for example 例如
This is the Text 这是文本
XmlNode xmlType = doc.DocumentElement.SelectSingleNode("/job/type");
xmlType.innerText = "This is the Text";
xmlType.Value = "Stack";
尝试这个:
string str = xmltype.Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.