简体   繁体   中英

Load XML in C# InnerText

I have a C# service where I loop every 1 seconds trough a directory looking for XML files.

These XML files may look like this:

<?xml version="1.0" encoding="UTF-8"?>
<job>
<type>freelance</type>
<text>blah</text>
</job>

In a foreach I do the following:

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. Documentation on MSDN does not provide me with anything new and I would like to know what I am doing wrong.

This following console program will output "freelance". I think the issue may be with some of your XML - do all of your XML docs follow the same schema? I am guessing that the code fails with a NullReferenceException at some point. 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.

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. after that take the one particular node check for 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM