[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1848
  • Last Modified:

read xml file to find a node value

I'm trying to read an xml file and find a node. if the node exists i want to read the contents. if not then show a message not found. below is my code but it isn't working.

protected void test3()
{
//example of xml files:
//1. has a node <data><a>/9j/4AAQSkZJRgABAQEASABIAAD/4QICRXhpZgAATU0AKgAAAAgACQEPAAIAAAAGAAAAegEQAAIAAAA</a></data>
//2. no a node <data></data>

string Data = "";
            XmlElement dataElement;

            XmlDocument doc = new XmlDocument();
            doc.Load(cmbxFiles.SelectedValue.ToString());
            
            XmlNodeList dataList = doc.GetElementsByTagName("Data");

            foreach (XmlNode node in dataList)
            {
                dataElement = (XmlElement)node;

                Data = dataElement.GetElementsByTagName("a")[0].InnerText;               
            }

            label1.Text = Data.ToString();
}

Open in new window

0
fwstealer
Asked:
fwstealer
  • 6
  • 2
  • 2
  • +2
1 Solution
 
fwstealerAuthor Commented:
i change the code a bit:

string fileReading = cmbxFiles.SelectedValue.ToString();

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(fileReading);

            XmlNode currentVin = doc.LastChild;
            string xmlVin = currentVin.ChildNodes[1].InnerText;

            lblA.Text = xmlVin.ToString(); // finds: /9j/4AAQSkZJRgABAQEASABIAAD/4QICRXhpZgAATU0AKgAAAAgACQEPAAIAAAAGAAAAegEQAAIAAAA

Open in new window


but it doesn't render it to the label.
0
 
fwstealerAuthor Commented:
nevermind - realized the string was too big for the label so i used textbox multiline.

but how do i check if the <a> node exists?
0
 
Miguel OzSoftware EngineerCommented:
Use Xpath syntax to search for nodes:
XmlNodeList nodeList = doc.SelectNodes("//a");
//check if
nodeList != null && nodeList.Count > 0

Check:
http://www.aspfree.com/c/a/.NET/Working-with-XPath-The-NET-Way/
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
fwstealerAuthor Commented:
how would i integrate that into my code? does XmlNodeList nodeList = doc.SelectNodes("//a"); fit in after i open thefile?

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(fileReading);
XmlNodeList nodeList = doc.SelectNodes("//a");
            if (nodeList.Count > 0)
            {
                XmlNode currentVin = doc.LastChild;
                string xmlVin = currentVin.ChildNodes[1].InnerText;
                textBox1.Text = xmlVin.ToString();
            }
            else
            {
                textBox1.Text = "not found";
            }

Open in new window

0
 
fwstealerAuthor Commented:
i tried the following but it didn't produce anything

            XPathDocument Doc = new XPathDocument(fileReading);
            XPathNavigator navigator = Doc.CreateNavigator();
            XPathNodeIterator iterator = navigator.Select("/data/a");
            while (iterator.MoveNext())
            {
                textBox1.Text = iterator.Current.Value.ToString();
            }

Open in new window

0
 
HooKooDooKuCommented:
What do you mean that your example code didn't produce anything?  If you simply ran that code, as apposed to stepping through it in debug mode, then nothing MIGHT be exactly what you would expect to see.

Each time through the while loop, you are over-writing the text in the text box.  So if the final matching node is a blank or empty note, then a blank text box is exactly what you would see.  Keep in mind, the contents of the text box are not going to get redrawn each time through the loop.  The text box is not going to repaint itself until it gets the opportunity to process a paint message, so even though the internal text storage for the text box would update at the loop processes, the window itself would never update until the while loop finished executing, so the only thing that would ever get drawn would be the value from the last node.

Now I don't know the details of using this particular iterator.  (Last time I delt with XML I was accessing nodes via indexes... like your example using child nodes via an index).  But I could see the possibility that this iterator works something like navigating a database record set, a for loop, or reading a file.  In those cases, you don't know you've reached the end of the data until the last read/iterator is logically beyond the end.  So you would also need to check to make sure the last MoveNext didn't result in moving past the last matching record, and therefore the last iteration for the while loop might be reading a blank value (not sure what so ever, but you might need to look into that to learn exactly how this iterator works).
0
 
Shahan AyyubSenior Software Engineer - iOSCommented:
Check this out:

       XmlDocument xDoc= new XmlDocument();
        xDoc.Load(@"..\..\XMLFile1.xml");
        XmlNode xmlnode= xDoc.SelectSingleNode("data/a");
        string data = string.Empty;

        if (typeof(XmlNode).IsInstanceOfType(xmlnode))
        {
            data = xmlnode.InnerText; // here is your data of node "<a>"
        }

Open in new window


Does it help ?
0
 
fwstealerAuthor Commented:
i debugged the code and below is what i have:

string fileReading = cmbxFiles.SelectedValue.ToString(); //value is "\\\\server\\folder\\folder\\file.xml"

xdoc -- innerxml has the contents of the xml file

XmlNode xmlnode = xDoc.SelectSingleNode("data/a"); //null

Open in new window


so it can open the file but it isn't getting the value
0
 
HooKooDooKuCommented:
The thing I think you might be missing is that you have to start with a top level node... NOT the Document.

Here is some sample VB code I've written that used MXSML2 and DOM to read the XML file.  It obviously a little different from the XML libarary you are using, but it might help point you in the right direction understanding how another XML library has worked in the past.

The following example code opens an XML file, declares that XPath is being used, selects all <Data> nodes that are off the root note, and then passes the text of the node to a function ProcessNodeValue()
Dim Doc As MSXML2.DOMDocument40
Dim RootNode as MSXML2.IXMLDOMElement
Dim NodeList as MSXML2.IXMLDOMNodeList
Dim Count as Integer
Dim I as Integer

Set Doc = New DOMDocument40
Doc.async = False
Doc.Load(FileName)
Call Doc.setProperty("SelectionLanguage", "XPath")    'Allow XPath Queries
set RootNode = m_Doc.documentElement
Set NodeList = New MSXML2.IXMLDOMNodeList
NodeList.selectNodes("./Data")
Count = NodeList.Length
For I = 0 To Count - 1
    Call ProcessNodeValue( NodeList.Item(I).nodeTypedValue
Next I

Open in new window

0
 
fwstealerAuthor Commented:
the following returns the data in the a tag - which is what i want eventually:
string fileReading = cmbxFiles.SelectedValue.ToString();
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(fileReading);

XmlNode currentVin = doc.LastChild;
string xmlVin = currentVin.ChildNodes[1].InnerText;
textBox1.Text = xmlVin.ToString();

Open in new window


but how do i check the xml file to see if the a tag is present?


i tried this - when i debug i see the data tag and the a tag in the innerxml property so i know the tag is there.
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(fileReading);
            XmlNode node = doc.GetElementsByTagName("a")[1];
                //.SelectSingleNode("a");
            if (node != null)
            {
                XmlNode currentVin = doc.LastChild;
                string xmlVin = currentVin.ChildNodes[1].InnerText;
                textBox1.Text = xmlVin.ToString();
            }
            else
            {
                textBox1.Text = "";
            }

Open in new window


driving me nuts
0
 
Shahan AyyubSenior Software Engineer - iOSCommented:
ok so check this plz:

            string xmlVin = string.Empty;
            if (doc.GetElementsByTagName("a").Count > 0)
            {
                foreach (XmlNode n in doc.GetElementsByTagName("a"))
                {
                    if (n != null)
                    {
                        XmlNode currentVin = doc.LastChild;
                        xmlVin = currentVin.ChildNodes[1].InnerText;
                    }
                }
            }
            textBox1.Text = xmlVin.ToString();

Open in new window


In the inner if... bloxk, You can iterate on ChildNodes as well like:
foreach( XmlNode child in currentVin.ChildNodes)
{
 xmlVin = child.InnerText;
 
}

Open in new window

0
 
Miguel OzSoftware EngineerCommented:
You issue may be two things:
- The nodes are a zero-based collection, thus your orignal code has to be modified as:
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(fileReading);
XmlNodeList nodeList = doc.SelectNodes("/data/a");
            if (nodeList.Count > 0)
            {
                XmlNode currentVin = doc.LastChild;
                string xmlVin = nodeList.Item(0).InnerText;
                textBox1.Text = xmlVin.ToString();
            }
            else
            {
                textBox1.Text = "not found";
            } 

Open in new window

IF this code does not work, you need to check whether your xml is using a namespace, check:
http://support.microsoft.com/kb/318545
0
 
DhaestCommented:
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 6
  • 2
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now