Solved

Copy Multiple XmlElements into a New XmlDocument?

Posted on 2014-03-03
9
313 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
ID: 39901695
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
ID: 39901705
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
ID: 39901849
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
ID: 39901935
What is the structure of your underlying xml, could you show??
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:Conrado ZAVALA
ID: 39903308
<?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
ID: 39903313
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
ID: 39905004
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
ID: 39908245
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
ID: 39909821
Thank you very much...
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

863 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

22 Experts available now in Live!

Get 1:1 Help Now