Hy at all, i am new in C# programming so maybe this is a easy question. I try to read an XML-file with XDocument and write out the local name of a Element as string.
For the output i use the listing window of SiemensNX but every other output window or txt-file is suitable.
Here is the Input-XML:
<?xml version="1.0" encoding="utf-8"?>
<Rootlvl>
<Lvl_1>
<Lvl_2/>
</Lvl_1>
</Rootlvl>
Here is the C# code:
using System.Xml.Linq;
using NXOpen;
namespace XmlElementName
{
class Program
{
private static ListingWindow lw = s.ListingWindow;
public static void Main()
{
string XmlFilePath = @"C:\Users\XXX\Desktop\TestXML.xml"; //XML path
string testnode = "Lvl_2"; //local name of a optional XML element
lw.Open(); //open NX listinwindow for output
//=============LoadXmlFile================
//get main Input
XDocument xml = XDocument.Load(XmlFilePath); //load XmlFile
//====================WriteOutElementName====================
XElement node;
if (testnode == null) //if no optional Element name --> take root element of XML
{
node = xml.Root;
}
else
{
// Find node to passed string "testnode" --> here "Lvl_2"
node = xml.Element(testnode);
}
lw.WriteLine("Test"); //Test if output works --> !yes it works
if(node != null)
{
string output = node.Name.LocalName;
//local name of XElement-variable "node" to string
lw.WriteLine(output); //output the local name of variable "node"
}
else
{
lw.WriteLine("Element with Name = " + testnode + "not found")
}
}
}
}
The Output if variable testnode = "Lvl_2" should be:
Test
Lvl_2
The Output if variable testnode = null schould be:
Test
Rootlvl
The VS Debugger show me that
node = xml.Element(testnode); //testnode = Lvl_2
can't find an element in the XML with the the name "Lvl_2". So it set "node" to "Null" and throw the following exeption:
"System.NullReferenceException: Object reference not set to an instance of an object."
But i know that "Lvl_2" is a subelement of the XML. What can i do to found this element "Lvl_2" in the XML?
What should i change in this line
node = xml.Element(testnode)
to find the element by name?
Thanks for your help guys.