简体   繁体   中英

Add null as value when element does not exist in XML file C#

In C# I'm using the following to get some elements from an XML file:

var TestCaseDescriptions = doc.SelectNodes("//testcase/htmlcomment");

This works fine and gets the correct information but when my testcase has no htmlcomment it won't add any entry in the XmlNodeList TestCaseDescriptions.

When there's not htmlcomment I would like to have the value "null" as string the TestCaseDescriptions. So in the end I would have an XMLNodeList like

htmlcomment

htmlcomment

null

htmlcomment

htmlcomment

Can anyone describe or create a sample how to make this happen?

 var TestCaseDescriptions = doc.SelectNodes("//testcase/htmlcomment"); 

When there's not htmlcomment I would like to have the value "null" as string the TestCaseDescriptions.

Your problem comes from the fact that if there is no htmlcomment , the number of selected nodes will be one less. The current answer shows what to do when the htmlcomment element is present, but empty, but I think you need this instead, if indeed the whole htmlcomment element is empty:

var testCases = doc.SelectNodes("//testcase");
foreach (XmlElement element in testCases)
{
    var description = element.SelectSingleNode("child::htmlcomment");
    string results = description == null ? "null" : description.Value;
}​

In above code, you go over each test case, and select the child node htmlcomment of the test case. If not found, SelectSingleNode returns null , so the last line checks for the result and returns "null" in that case, or the node's value otherwise.

To change this result into a node, you will have to create the node as a child to the current node. You said you want an XmlNodeList, so perhaps this works for you:

var testCaseDescriptions = doc.SelectNodes("//testcase");
foreach (XmlElement element in testCaseDescriptions)
{
    var comment = element.SelectSingleNode("child::htmlcomment");
    if (comment == null)
    {
        element.AppendChild(
            doc.CreateElement("htmlcomment")
            .AppendChild(doc.CreateTextNode("none")));
    }
}​

After this, the node set is updated.


Note: apparently, the OP mentions that element.SelectSingleNode("child::htmlcomment"); does not work, but element.SelectSingleNode("./htmlcomment"); does, even though technically, these are equal expressions from the point of XPath, and should work according to Microsoft's documentation.

Try this

XmlDocument doc = new XmlDocument();
var TestCaseDescriptions = doc.SelectNodes("//testcase/htmlcomment");
foreach (XmlElement element in TestCaseDescriptions)
{
    string results = element.Value == null ? "" : element.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