Solved

Copy Multiple XmlElements into a New XmlDocument?

Posted on 2014-03-03
9
309 Views
Last Modified: 2014-03-06
Hello guys...
I have this problem today...

I have a windows form winform
this windows form loads an xml document, and when I use the first, next, previous and last buttons, they move between the persons elements, what I want to do is:

when you write something on the txtLastName and you click on the find button (is working good), what I want is to copy those elements of the query into a new xml document...

Why?
cause I want the results to be showed in the textboxes, and i need that the first, next, previous and last buttons to make me move between the query elements that are in the new xml document.

here is the code that im using:

Button Next:
private void btnNext_Click(object sender, EventArgs e)
        {            
            current = (current + 1 > max) ? max : current + 1;
            currentPerson = (XmlElement)root.ChildNodes[current];
            ShowDetails(currentPerson);
            if (current >= max)
            {
                MessageBox.Show("No More Persons in the XML", "Done");           
            }            

        }

Open in new window


Button Find:
private void btnFind_Click(object sender, EventArgs e)
        {
            string keyword = txtLastName.Text;
            var NewoXmlDoc = XDocument.Load(@"C:\people2.xml");           
            

            var query = NewoXmlDoc.Descendants()
                .Where(x => !x.HasElements &&
                            x.Value.IndexOf(keyword, StringComparison.InvariantCultureIgnoreCase) >= 0);
            foreach (var element in query)            
            {
                string uFirstName = element.Parent.Element("FirstName").Value;
                string uLastName = element.Value;

                txtName.Text = uFirstName;
                txtLastName.Text = uLastName;                
            }     
        }

Open in new window


thanks in advance..!!
0
Comment
Question by:Conrado ZAVALA
  • 5
  • 4
9 Comments
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
A bit lost :).

So, do you want to copy found elements from the existing XmlDocument to a new one?

Or do you want insert search strings into a new XmlDocument?

Really, copying elements from one document to another you may achieve by "importing" elements:

http://msdn.microsoft.com/en-us/library/kh91w6fw(v=vs.110).aspx
0
 

Author Comment

by:Conrado ZAVALA
Comment Utility
xD is a lil bit confusing... I want found elements from the existing xmldocument to a new xmldocument... :D
0
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
Hmmm...

I prefer XmlDocuments... :).

In your case I think you may 1. find an element in XDocument, grab all the required info, create new XElements and add them to your "search" results XDocument, like in the second part of http://www.c-sharpcorner.com/uploadfile/babu_2082/xmldocument-dom-and-xdocument-linq/.

Not sure if it helps ...
0
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
What is the structure of your underlying xml, could you show??
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:Conrado ZAVALA
Comment Utility
<?xml version="1.0" encoding="UTF-8" ?>
<People Count="8">
      <Person ID="1">
            <FirstName>Rodrigo</FirstName>
            <LastName>RIVERA</LastName>
      </Person>
      <Person ID="2">
            <FirstName>Conrado</FirstName>
            <LastName>ZAVALA</LastName>
      </Person>
      <Person ID="3">
            <FirstName>Ramon</FirstName>
            <LastName>ZAVALA</LastName>
      </Person>
      <Person ID="4">
            <FirstName>Jaime</FirstName>
            <LastName>SEGURA</LastName>
      </Person>
      <Person ID="5">
            <FirstName>Maria</FirstName>
            <LastName>ZAVALA</LastName>
      </Person>
      <Person ID="6">
            <FirstName>Carlos</FirstName>
            <LastName>SEGURA</LastName>
      </Person>
      <Person ID="7">
            <FirstName>Lorenzo</FirstName>
            <LastName>ZAVALA</LastName>
      </Person>
      <Person ID="8">
            <FirstName>Fabiana</FirstName>
            <LastName>POSADAS</LastName>
      </Person>
</People>

hey this is my xml structure..!!
0
 

Author Comment

by:Conrado ZAVALA
Comment Utility
I want the next and previous button to show me the search results in the textboxes..!!
0
 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 total points
Comment Utility
OK, I've written some code, hope now it helps :).
I believe code is self-explanatory but if you have problems - just ask.
My xml is in debug folder.
I didn't care about handling not loaded xml, etc.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace XmlPerson
{
    public partial class Form1 : Form
    {

        XmlDocument dbDoc = null;
        XmlDocument searchDoc = null;
        XmlElement docEle = null;
        int currentIndex = -1;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            dbDoc = new XmlDocument();
            dbDoc.Load("people.xml");
            searchDoc = new XmlDocument();
             docEle = searchDoc.CreateElement("People");
            searchDoc.AppendChild(docEle);
        }

        /// <summary>
        /// Find
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            XmlNodeList persons = dbDoc.GetElementsByTagName("Person");
            foreach (XmlNode pNode in persons)
            {
                XmlElement person = (XmlElement)pNode;
                if (((XmlElement)(person.ChildNodes.Item(0))).InnerText.ToLower() == this.txtFirstName.Text.ToLower())
                {
                    XmlElement newEle = (XmlElement)searchDoc.ImportNode(pNode, true);
                    docEle.AppendChild(newEle);
                    //increase current index for serached xml
                    currentIndex =  docEle.ChildNodes.Count - 1;
                    // display current node
                    displayPerson(newEle);
                }
            }
        }

        private void displayPerson(XmlElement person)
        {
            if (person == null)
            {
                return;
            }
            string firstName = ((XmlElement)(person.ChildNodes.Item(0))).InnerText;
            string lastName = ((XmlElement)(person.ChildNodes.Item(1))).InnerText;
            txtFirstName.Text = firstName;
            txtLastName.Text = lastName;
        }

        private void displaySearchResultByIndex(int index)
        {
            XmlElement toShow = (XmlElement)(docEle.ChildNodes.Item(index));
            displayPerson(toShow);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (currentIndex > 0)
            {
                currentIndex -= 1;
            }
            displaySearchResultByIndex(currentIndex);
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (currentIndex < docEle.ChildNodes.Count-1)
            {
                currentIndex += 1;
            }
            displaySearchResultByIndex(currentIndex);
        }
    }
}

Open in new window

0
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
I forgot to put some comments.
"I want the next and previous button to show me the search results in the textboxes..!!"

This works. But Search works for the "first name"  field only, I didn't bother with complex solutions :). So, this is not a final solution :).
0
 

Author Closing Comment

by:Conrado ZAVALA
Comment Utility
Thank you very much...
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now