Solved

Copy Multiple XmlElements into a New XmlDocument?

Posted on 2014-03-03
9
319 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 39901935
What is the structure of your underlying xml, could you show??
0
 

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

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…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

786 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