Solved

Copy Multiple XmlElements into a New XmlDocument?

Posted on 2014-03-03
9
327 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

808 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