I am trying to update the content of multiple nodes that match a specific xpath. For example, in the below example, I want to update any attribute1 node that currently is '2' with 'Hello'. What is the best way to do this?
(DotNetFiddle Here)
using System;
using System.IO;
using System.Xml;
using System.Linq;
public class Program
{
public static void Main()
{
XmlDocument job = new XmlDocument();
job.LoadXml(#"<parent>" +
"<report>" +
"<main>" +
"<attribute1>2</attribute1>"+
"<attribute1>2</attribute1>"+
"<attribute1>3</attribute1>"+
"</main>"+
"</report>" +
"</parent>");
string newAttribute1Value = "Hello";
//How do I update both attribute1's where value=2?
}
This may could help you :
using System;
using System.IO;
using System.Xml;
using System.Linq;
public class Program
{
public static void Main()
{
XmlDocument job = new XmlDocument();
job.LoadXml(#"<parent>" +
"<report>" +
"<main>" +
"<attribute1>2</attribute1>"+
"<attribute1>2</attribute1>"+
"<attribute1>3</attribute1>"+
"</main>"+
"</report>" +
"</parent>");
string newAttribute1Value = "Hello";
//How do I update both attribute1's where value=2?
// getting the list of nodes with XPath query :
XmlNodeList nodes = job.SelectNodes("//attribute1[text()=2]");
foreach (XmlNode child in nodes)
{
// replacing the old value with the new value
child.InnerText = newAttribute1Value ;
}
}
Related
<ce_table frame="topbot" id="t0010" rowsep="0" colsep="0">
<ce_label>Table 2</ce_label>
<ce_caption id="cn040">
<ce_simple-para id="spar055">Model fit cnbs for the span targeted moments.</ce_simple-para>
</ce_caption>
</ce_label>
</ce_table>
I need to change id="t0010" to id="tf0010" and id="cn.. " to id="cib.. ".
I only need to change prefix of an attribute value.
Use xml linq :
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement ce_table = doc.Descendants("ce_table").First();
ce_table.SetAttributeValue("id", "tf0010");
XElement ce_caption = ce_table.Descendants("ce_caption").First();
ce_caption.SetAttributeValue("id", "cib040");
}
}
}
I have been trying hard to parse an xml string, but all to no avail
<EnquirySingleItemResponse xmlns="http://tempuri.org/"> <EnquirySingleItemResult>
<Response>
<MSG>SUCCESS</MSG>
<INFO>TESTING</INFO>
</Response> </EnquirySingleItemResult> </EnquirySingleItemResponse>
My Code returns null or the texts in the xml tags no matter how i parse it. I have checked some post, but they seem not to be working.
See my code snipped below
XElement anotherUnwrappedResponse = ( from _xml in axdoc.Descendants(tempuri + "EnquirySingleItemResponse")
select _xml).FirstOrDefault();
string response = anotherUnwrappedResponse.Value;
axdoc.Descendants is used because i unwrapped the soap body, to have the xml above
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input =
"<EnquirySingleItemResponse xmlns=\"http://tempuri.org/\">" +
"<EnquirySingleItemResult>" +
"<Response>" +
"<MSG>SUCCESS</MSG>" +
"<INFO>TESTING</INFO>" +
"</Response> </EnquirySingleItemResult> </EnquirySingleItemResponse>";
XDocument doc = XDocument.Parse(input);
string msg = doc.Descendants().Where(x => x.Name.LocalName == "MSG").FirstOrDefault().Value;
string info = doc.Descendants().Where(x => x.Name.LocalName == "INFO").FirstOrDefault().Value;
}
}
}
i am trying to add XmlNodes from one XmlDocument to another as a new node.
My main issue is that i can import only the First or Last child of the document but not the ones in between. all of the nodes i am trying to import have the same layout but i cant seem to create any iteration for importing them all since i can only select either the FirstChild or LastChild - Please note this is also across 2 forms.
I am new to Xml but do not want to re-write my whole Xml Document over again in an XDocument, any help would be greatly appreciated, Thanks.
Code Below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace XmlCreator
{
public partial class Form_Member : Form
{
string MPlayID, MNick, MName, MMail, MICQ, MRemark;
public static XmlDocument xmlMembers = null;
static XmlNode rootNode = null;
public Form_Member()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (xmlMembers != null)
{
XmlNode member = xmlMembers.CreateElement("member");
XmlAttribute attID = xmlMembers.CreateAttribute("id");
attID.Value = MPlayID;
member.Attributes.Append(attID);
XmlAttribute attNick = xmlMembers.CreateAttribute("nick");
attNick.Value = MNick;
member.Attributes.Append(attNick);
rootNode.AppendChild(member);
XmlNode MNameNode = xmlMembers.CreateElement("name");
MNameNode.InnerText = MName;
member.AppendChild(MNameNode);
XmlNode MMailNode = xmlMembers.CreateElement("email");
MMailNode.InnerText = MMail;
member.AppendChild(MMailNode);
XmlNode MICQNode = xmlMembers.CreateElement("icq");
MICQNode.InnerText = MICQ;
member.AppendChild(MICQNode);
XmlNode MRemarkNode = xmlMembers.CreateElement("remark");
MRemarkNode.InnerText = MRemark;
member.AppendChild(MRemarkNode);
xmlMembers.Save("memberXML.xml");
clearTextFields();
}
}
private void Form_Member_Load(object sender, EventArgs e)
{
xmlMembers = new XmlDocument();
rootNode = xmlMembers.CreateElement("members");
xmlMembers.AppendChild(rootNode);
}
}
}
This is the form of which the Xml file i am trying to import is being created from, i am trying to import this to another form with the following code on the form i am trying to import it to.
code below:
XmlNode memberNode = xmlSquad.ImportNode(Form_Member.xmlMembers.DocumentElement.FirstChild, true);
xmlSquad.DocumentElement.AppendChild(memberNode);
To conclude, it is importing the FirstChild, however, i am making more than 1 memberNode in the xmlMembers.xml file from the other form which i can't find a way of copying over.
Any help will be appreciated, Thank you.
You need the following extension method:
public static class XmlNodeExtensions
{
/// <summary>
/// Copy all child XmlNodes from the source to the destination.
/// </summary>
/// <param name="source">Copy children FROM this XmlNode</param>
/// <param name="destination">Copy children TO this XmlNode</param>
public static void CopyChildren(this XmlNode source, XmlNode destination)
{
if (source == null || destination == null)
throw new ArgumentNullException();
var doc = destination.OwnerDocument;
if (doc == null)
throw new InvalidOperationException("null document");
// Clone the array to prevent infinite loops when the two nodes are from the same document.
foreach (var child in source.ChildNodes.Cast<XmlNode>().ToArray())
{
var copy = doc.ImportNode(child, true);
destination.AppendChild(copy);
}
}
}
You can then use it like:
Form_Member.xmlMembers.DocumentElement.CopyChildren(xmlSquad.DocumentElement);
I am trying to grab the specific value of an attribute in:
http://data.alexa.com/data?cli=10&dat=snbamz&url=bing.com
<SD>
<POPULARITY URL="bing.com/" TEXT="16" SOURCE="panel"/>
<REACH RANK="16"/>
<RANK DELTA="-7"/>
<COUNTRY CODE="US" NAME="United States" RANK="9"/>
</SD>
</ALEXA>
I want to grab the value of
I have the current Console Code for this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string url = "http://data.alexa.com/data?cli=10&dat=snbamz&url=bing.com";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(url);
XmlNode root = xmldoc.SelectSingleNode("//#RANK");
//XmlNamespaceManager xnm1 = new XmlNamespaceManager(xmldoc.NameTable);
//XmlNodeList nList1 = xmldoc.SelectNodes("//#RANK", xnm1);
Console.WriteLine(root.ToString());
Console.ReadLine();
}
}
}
But when I run it, I receive the following message in return:
System.Xml.XmlAttribute
What am I doing wrong?
Try changing:
Console.WriteLine(root.ToString());
to:
Console.WriteLine(root.Value);
Hope that helps.
The XML file is like this,There are about 20 Nodes(modules) like this.
<list>
<module code="ECSE502">
<code>ECSE502</code>
<name>Algorithms and Data structures</name>
<semester>1</semester>
<prerequisites>none</prerequisites>
<lslot>0</lslot>
<tslot>1</tslot>
<description>all about algorythms and data structers with totorials and inclass tests</description>
</module>
</list>
I did the following code. But when I debugged it it even didn't went inside to foreach function.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ModuleEnrolmentCW
{
class XMLRead
{
public string[] writeToXML(string s)
{
string text = s;
string[] arr = new string[6];
XmlDocument xml = new XmlDocument();
xml.Load("modules.xml");
XmlNodeList xnList = xml.SelectNodes("list/module[#code='" + text + "']");
foreach (XmlNode xn in xnList)
{
arr[0] = xn.SelectSingleNode("code").InnerText;
arr[1] = xn.SelectSingleNode("name").InnerText;
arr[2] = xn.SelectSingleNode("semester").InnerText;
arr[3] = xn.SelectSingleNode("prerequisites").InnerText;
arr[4] = xn.SelectSingleNode("lslot").InnerText;
arr[5] = xn.SelectSingleNode("tslot").InnerText;
}
return arr;
}
}
}
Please tell me where is the wrong??
Here is the rest of the code
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;
namespace ModuleEnrolmentCW
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string selected;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
XMLRead x = new XMLRead();
selected = (string)listBox1.SelectedItem;
string[] arr2 = x.writeToXML(selected);
label11.Text = arr2[0];
}
}
}
Make sure you are specifying correct path for your xml file.
It is working for me.
This line:
XmlNodeList xnList = xml.SelectNodes("list/module[#code='" + text + "']");
should read:
XmlNodeList xnList = xml.SelectNodes("list/module"); //Does not answer full scope of the question
Edit following a reread of the question:
The OP's code works fine in my tests. Either the file path is not correct, or the the string s passed into text matches the case of the Code value by which you are reading the nodes.
The SelectNodes XPath as you have it is case sensitive.
You appear to be working with XPath V1.0 which doesn't appear to support out of the box case insensitivity if that's a issue. See this link for a way to perform case insensitive XPath searches: http://blogs.msdn.com/b/shjin/archive/2005/07/22/442025.aspx
See also this link: case-insensitive matching in xpath?
Your code is correct, if the input is really the one you shown, and s point to an actual present code. Since you are pointing the file by a relative path, ensure you are loading the file you really expect.
Found the error. I was passing a wrong value to writeToXML method. Insted of passing code, I have passed name