In my MakeEnvelope method, I have added an event notification as follows:
var en = new EventNotification
{
Url = "<Listener URL>",
LoggingEnabled = "true",
RequireAcknowledgment = "true",
EnvelopeEvents = new List<EnvelopeEvent>
{
new EnvelopeEvent
{
EnvelopeEventStatusCode = "Completed",
IncludeDocuments = "true"
},
new EnvelopeEvent
{
EnvelopeEventStatusCode = "Delivered",
IncludeDocuments = "false"
},
new EnvelopeEvent
{
EnvelopeEventStatusCode = "Sent",
IncludeDocuments = "false"
}
}
};
envelopeDefinition.EventNotification = en;
I get the following XML response (I removed the Names and Emails, and changed the Guids):
<?xml version="1.0" encoding="utf-8"?><DocuSignEnvelopeInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.docusign.net/API/3.0"><EnvelopeStatus><RecipientStatuses><RecipientStatus><Type>Signer</Type><Email>someEmail#email.com</Email><UserName>SomeUserName</UserName><RoutingOrder>1</RoutingOrder><Sent>2021-04-28T14:14:41.163</Sent><Delivered>2021-04-28T14:14:54.997</Delivered><Signed>2021-04-28T14:14:59.73</Signed><DeclineReason xsi:nil="true" /><Status>Completed</Status><RecipientIPAddress>IP Address</RecipientIPAddress><ClientUserId>The ClientId</ClientUserId><CustomFields /><TabStatuses><TabStatus><TabType>SignHere</TabType><Status>Signed</Status><XPosition>938</XPosition><YPosition>1169</YPosition><TabLabel>Sign Here</TabLabel><TabName>SignHere</TabName><TabValue /><DocumentID>3</DocumentID><PageNumber>1</PageNumber></TabStatus></TabStatuses><AccountStatus>Active</AccountStatus><RecipientId>f571daaf-cd2c-4fge-a72e-d32277929305</RecipientId></RecipientStatus><RecipientStatus><Type>Signer</Type><Email>anotherEmail.Email.com</Email><UserName>Another Name</UserName><RoutingOrder>1</RoutingOrder><Sent>2021-04-28T14:14:41.503</Sent><DeclineReason xsi:nil="true" /><Status>Sent</Status><RecipientIPAddress /><CustomFields /><TabStatuses><TabStatus><TabType>SignHere</TabType><Status>Active</Status><XPosition>196</XPosition><YPosition>1169</YPosition><TabLabel>Sign Here</TabLabel><TabName>SignHere</TabName><TabValue /><DocumentID>3</DocumentID><PageNumber>1</PageNumber></TabStatus></TabStatuses><AccountStatus>Active</AccountStatus><RecipientId>1eb9d346-33ae-4444-b5f1-be30f8bcf041</RecipientId></RecipientStatus></RecipientStatuses><TimeGenerated>2021-04-28T14:15:03.3011225</TimeGenerated><EnvelopeID>3c9281c7-3345-44ac-9c4f-3d39274c49f4</EnvelopeID><Subject>Please sign this document</Subject><UserName>User Name</UserName><Email>Users Email Address Here</Email><Status>Sent</Status><Created>2021-04-28T14:14:40.41</Created><Sent>2021-04-28T14:14:41.557</Sent><ACStatus>Original</ACStatus><ACStatusDate>2021-04-28T14:14:40.41</ACStatusDate><ACHolder>Account Holders name</ACHolder><ACHolderEmail>Account Holders Email</ACHolderEmail><ACHolderLocation>DocuSign</ACHolderLocation><SigningLocation>Online</SigningLocation><SenderIPAddress>Senders IP Address</SenderIPAddress><EnvelopePDFHash /><CustomFields /><AutoNavigation>true</AutoNavigation><EnvelopeIdStamping>true</EnvelopeIdStamping><AuthoritativeCopy>false</AuthoritativeCopy><DocumentStatuses><DocumentStatus><ID>3</ID><Name>PG Document</Name><TemplateName /><Sequence>1</Sequence></DocumentStatus></DocumentStatuses></EnvelopeStatus></DocuSignEnvelopeInformation>
I was having issues parsing the response, so I created a console application to parse the xml string, and using the response xml shown above. The following is the code that I used to parse.
static void Main(string[] args)
{
string strXML = GetXML();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strXML);
string xpath = "DocuSignEnvelopeInformation/EnvelopeStatus";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
Console.WriteLine(childrenNode.SelectSingleNode("//status").Value);
}
Console.Read();
}
nodes is always empty.
What am I missing here?
Thank you in advance.
I was able to get it to work by using the namespace it was using.
var ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("docusign", "http://www.docusign.net/API/3.0");
var envelopeId = xmlDoc.SelectSingleNode("//docusign:EnvelopeID", ns);
var status = xmlDoc.SelectSingleNode("//docusign:Status", ns);
I changed the method and I am able to get the values:
Request.InputStream.Position = 0;
var xmlDoc = new XmlDocument();
xmlDoc.Load(Request.InputStream);
var ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("docusign", "http://www.docusign.net/API/3.0");
var envelopeId = xmlDoc.SelectSingleNode("//docusign:EnvelopeID", ns);
var status = xmlDoc.SelectSingleNode("//docusign:EnvelopeStatus/docusign:Status", ns);
if (envelopeId == null || String.IsNullOrEmpty(envelopeId.InnerText) || status == null || string.IsNullOrEmpty(status.InnerText)) return;
if (status.InnerText.ToLower() == "completed")
{
// Update the Document Status
var extra = _uow.JobExtraRepository.GetByEnvelopeId(envelopeId.InnerText);
extra.StatusId = (int)ExtraJobStatus.Completed;
Save();
var docBytes = xmlDoc.SelectSingleNode("//docusign:docBytes", ns);
}
Related
I'm calling WebAPI and getting an XmlResult so I want to read this XML result and convert to Generic List.
Here my xml format
<SalesList xmlns="http://schemas.microsoft.com/2003/10/Serialization/"><row Total="103700.0000" Tip="Dry"/><row Total="9341.0000" Tip="Wet"/></SalesList>
I decode my XML and delete first node of XML and I can catch my pure XML but now when I try to fill list I cannot reach Elements("row")
Why? Have any idea?
Here my code
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8095/ ");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/xml"));
string link = "api/Values/GeneralReport";
var response = client.GetAsync(link).Result;
string res = "";
using (HttpContent content = response.Content)
{
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
XDocument doc = XDocument.Parse(res);
XElement firstChild = doc.Root.Elements().First();
string res1 = firstChild.ToString();
XDocument doc1 = XDocument.Parse(res1);
if (doc1.Root != null)
{
var listxml = (from r in doc1.Root.Elements("row")
select new StationInfo{
ItemType = (string)r.Element("Tip"),
Total = (decimal)r.Element("Total")}).ToList();
}
a) You don't use the xml namespace
b) Tip and Total are attributes, not elements
XNamespace ns = "http://schemas.microsoft.com/2003/10/Serialization/";
var listxml = XDocument.Parse(res)
.Descendants(ns + "row")
.Select(x => new
{
ItemType = (string)x.Attribute("Tip"),
Total = (string)x.Attribute("Total"),
})
.ToList();
I am trying to retrieve data from an XML file and return the parsed data in a list. Depending on what I use to access the data (Element or Attributes) I either get null (in case of Element) or something I cannot decipher (in case of Attributes).
XML Looks like this:
<DATA_RESPONSE>
<HEADER>
<MSGID>IS20101P:091317125610:98::34:0</MSGID>
</HEADER>
<DATA>
<ROW ID='IS20101P' PE_NAME='APP-029' PE_ID='4' CODE='4829' DATA='5,1,500,1' />
<ROW ID='IS20101P' PE_NAME='APPS-029' PE_ID='4' CODE='4829' DATA='4,1,500,1' />
...
</DATA>
<SUMMARY>
</SUMMARY>
<ERRORS>
</ERRORS>
</DATA_RESPONSE>
I am using the following to get the data. I read the file and store XML in a string and call a method with this string as argument:
public static Hashtable GetIDSData(string sXMLString)
{
Hashtable result = new Hashtable();
result.Add("Success", false);
result.Add("ErrorMessage", "");
result.Add("ID", "");
result.Add("PE_NAME", "");
result.Add("PE_ID", "");
result.Add("CODE", "");
result.Add("DATA", "");
xmlDoc.InnerXml = sXMLString;
XmlElement root = xmlDoc.DocumentElement;
XDocument doc = XDocument.Parse(sXMLString);
XmlNode node = xmlDoc.SelectSingleNode("DATA_RESPONSE/DATA");
if (node != null)
{
var AddressInfoList = doc.Root.Descendants("ROW").Select(Address => new
{
ID = Address.Attributes("ID")?.ToString(),
PEName = Address.Attributes("PE_NAME")?.ToString(),
PEID = Address.Attributes("PE_ID")?.ToString(),
Code = Address.Attributes("CODE")?.ToString(),
Data = Address.Attributes("DATA")?.ToString(),
}).ToList();
foreach (var AddressInfo in AddressInfoList)
{
if (string.IsNullOrEmpty(AddressInfo.Code))
{
result["Success"] = false;
result["ErrorMessage"] = "Invalid Code; code is empty.";
}
else
{
result["Success"] = true;
result["ErrorMessage"] = "";
result["ID"] = AddressInfo.ID;
result["PE_NAME"] = AddressInfo.PEName;
result["PE_ID"] = AddressInfo.PEID;
result["CODE"] = AddressInfo.Code;
result["DATA"] = AddressInfo.Data;
}
}
return result;
}
In Linq section, if I use Address.Element("ID").Value, I get null returned.
There is no namespace used in XML.
First off, the GetIDSData() method does not compile as is, because at the line xmlDoc.InnerXml = sXMLString, xmlDoc has not been defined.
I'm assuming you want xmlDoc to be an XmlDocument loaded with the contents of the sXMLString parameter, so I'm changing that line to:
XmlDocument xmlDoc = new XmlDocument {InnerXml = sXMLString};
Also, your root variable is never used, so I removed it for clarity.
Now as for the main part of your question, given your current syntax, you are calling .ToString() on a collection of attributes, which is obviously not what you want. To fix this, when you're iterating the AddressInfoList, You want to fetch the attribute values like:
ID = Address.Attributes("ID")?.Single().Value
or
ID = address.Attribute("ID")?.Value
...rather than Address.Attributes("ID")?.ToString() as you have above.
You are not selecting values of attributes. In your code you are selecting attributes. Not sure what are you trying to achieve, but here is my modified version of your code that loads all elements into DataTable
public static DataTable GetIDSData(string sXMLString)
{
DataTable result = new DataTable();
result.Columns.Add("Success");
result.Columns.Add("ErrorMessage");
result.Columns.Add("ID");
result.Columns.Add("PE_NAME");
result.Columns.Add("PE_ID");
result.Columns.Add("CODE");
result.Columns.Add("DATA");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.InnerXml = sXMLString;
XmlElement root = xmlDoc.DocumentElement;
XDocument doc = XDocument.Parse(sXMLString);
XmlNode node = xmlDoc.SelectSingleNode("DATA_RESPONSE/DATA");
if (node != null)
{
var AddressInfoList = doc.Root.Descendants("ROW").Select(Address => new
{
ID = Address.Attributes("ID").Select(i=>i.Value) ,
PEName = Address.Attributes("PE_NAME").Select(i=>i.Value),
PEID = Address.Attributes("PE_ID").Select(i=>i.Value),
Code = Address.Attributes("CODE").Select(i=>i.Value),
Data = Address.Attributes("DATA").Select(i=>i.Value),
}).ToList();
AddressInfoList.ForEach(e =>
{
e.Code.ToList().ForEach(c =>
{
DataRow row = result.NewRow();
if (!string.IsNullOrEmpty(c))
{
row["Success"] = true;
row["ErrorMessage"] = "";
row["ID"] = e.ID.First();
row["PE_NAME"] = e.PEName.First();
row["PE_ID"] = e.PEID.First();
row["CODE"] = e.Code.First();
row["DATA"] = e.Data.First();
}
else
{
row["Success"] = false;
row["ErrorMessage"] = "Invalid Code; code is empty.";
}
result.Rows.Add(row);
});});
result.Dump();
return result;
}
return result;
}
And this is the result that you will get in your datatable.
ID = Address.Attributes("ID")?.ToString(),
You want to use Attribute(name) (without s) instead:
ID = Address.Attributes("ID")?.Value,
i'm trying to read xml file and update all it's value my xml was
<adf>
<prospect>
<requestdate>2015-10-29 07-38-22</requestdate>
<id sequence="1" source="admin.ss.com">admin.ss.com</id>
<vehicle interest="buy" status="">
<id sequence="1" source=""></id>
<year></year>
<make></make>
<model>camry</model>
<vin></vin>
<stock></stock>
<trim></trim>
</vehicle>
<customer>
<contact primarycontact="1">
<name part="first">Jessica</name>
<name part="last">Sonntag</name>
<email>js#test.com</email>
<phone type="phone" time="day">555-585-5555</phone>
<address>
<street line="1"></street>
<city></city>
<regioncode></regioncode>
<postalcode></postalcode>
<country></country>
</address>
</contact>
<comments>Vehicle Year: 2011 Comments: </comments>
</customer>
<provider>
<name part="full">ST</name>
<service> Engine Marketing</service>
<phone>1-866-572-3952</phone>
</provider>
</prospect>
</adf>
so i select node like below
var items = (from item in xmlDoc.Descendants("requestdate")
select item).ToList();
then i can update only requestdata tag value so do i have to repeat same for all tags or is there any good way to accomplish this.
Regards
There is an easy way to do this. This one is a hidden gem. Most people may not know this. This feature came in VS2013 and it's called "Paste XML as Classes."
Save your xml (Ex: MyXml.XML)
Create a new Console project
Open the Xml in Visual studio
Copy All contents of the xml (Ctl+A, Ctl + C)
Add a new class to your project. You can give any name you like.
Go to Edit>Paste Special>Paste XML as classes.
Add another class to your project. Then add below two methods to that class.
public static string Serialise<T>(T serialisableObject)
{
var doc = new XmlDocument();
using (var stream = new StringWriter())
{
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlWriter xmlWriter = XmlWriter.Create(stream, settings);
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(xmlWriter, serialisableObject, ns);
doc.LoadXml(stream.ToString());
}
return doc.InnerXml;
}
public static T Deserialise<T>(string xml)
{
T list;
using (var reader = new StringReader(xml))
{
var serialiser = new XmlSerializer(typeof(T));
list = (T)serialiser.Deserialize(reader);
}
return list;
}
Then in your console applications Main method; add this.
var myObj = new adf();
myObj.prospect = new adfProspect();
myObj.prospect.customer = new adfProspectCustomer(){comments = "dgsrtetetete"};
//populate all fields.....
var xml = MySerializer.Serialise(myObj);
File.WriteAllText(#"C:\myNewXml.xml", xml);
That's it. Same way now you can deserialise an xml object in to your class.
Try the XmlSerializer class: https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx If you serialize/deserialize the xml then up dating is trivial.
If you wanted to change every phone number to "0123456789" you could do something like:
var xDoc = XDocument.Load("document.xml");
var results = from phone in xDoc.Descendants("phone") select phone;
foreach (XElement result in results)
{
element.SetValue("0123456789");
}
i have came up with solution with support two extension method i'm iterating all nodes and update.(since my xml is not too big or complicated this one would be a good solution)
with help of these two extension methods
public static void IterateThroughAllNodes(this XmlDocument doc, Action<XmlNode> elementVisitor)
{
if (doc != null && elementVisitor != null)
{
foreach (XmlNode node in doc.ChildNodes)
{
DoIterateNode(node, elementVisitor);
}
}
}
public static void IterateThrough(this XmlNodeList nodes, Action<XmlNode> elementVisitor)
{
if (nodes != null && elementVisitor != null)
{
foreach (XmlNode node in nodes)
{
DoIterateNode(node, elementVisitor);
}
}
}
private static void DoIterateNode(XmlNode node, Action<XmlNode> elementVisitor)
{
elementVisitor(node);
foreach (XmlNode childNode in node.ChildNodes)
{
DoIterateNode(childNode, elementVisitor);
}
}
then i can update my xml nodes as below
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/xmlmail.xml"));
var email = new XmlEmail();
doc.IterateThroughAllNodes(
delegate(XmlNode node)
{
if (node.Name.Equals("requestdate"))
node.InnerText= email.RequestDate.ToLongDateString();
if (node.Name.Equals("vehicle"))
{
XmlNodeList childs = node.ChildNodes;
childs.IterateThrough(delegate(XmlNode vnode)
{
if (vnode.Name.Equals("id"))
vnode.InnerText= email.VehicleId.ToString();
if (vnode.Name.Equals("year"))
vnode.InnerText= email.Year.ToString();
if (vnode.Name.Equals("make"))
vnode.InnerText= email.Make;
if (vnode.Name.Equals("model"))
vnode.InnerText= email.Model;
if (vnode.Name.Equals("vin"))
vnode.InnerText= email.Vin;
if (vnode.Name.Equals("trim"))
vnode.InnerText = email.Trim;
});
}
if (node.Name.Equals("customer"))
{
XmlNodeList childs = node.ChildNodes;
childs.IterateThrough(delegate(XmlNode vnode)
{
if (vnode.Attributes != null && (vnode.Name.Equals("name") && vnode.Attributes["part"].Value.Equals("first")))
vnode.InnerText= email.FirstName;
if (vnode.Attributes != null && (vnode.Name.Equals("name") && vnode.Attributes["part"].Value.Equals("last")))
vnode.InnerText= email.LastName;
if (vnode.Name.Equals("email"))
vnode.InnerText= email.Email;
if (vnode.Name.Equals("phone"))
vnode.InnerText= email.Phone;
if (vnode.Name.Equals("comments"))
vnode.InnerText= email.Comments;
if (vnode.Name.Equals("address"))
{
XmlNodeList addresschilds = vnode.ChildNodes;
addresschilds.IterateThrough(delegate(XmlNode anode)
{
if (anode.Name.Equals("street"))
anode.InnerText= email.Street;
if (anode.Name.Equals("city"))
anode.InnerText= email.City;
if (anode.Name.Equals("phone"))
anode.InnerText= email.Phone;
if (anode.Name.Equals("regioncode"))
anode.InnerText= email.RegionCode;
if (anode.Name.Equals("postalcode"))
anode.InnerText= email.Postalode;
if (anode.Name.Equals("country"))
anode.InnerText= email.Country;
});
}
});
}
});
I am trying to serialize and insert a new created object into a specific child node of an XDocument. I've managed to accomplish this but my code seems smelly.
How can I test against a higher nodes attribute value without chaining through the Parent property like I have done below?
XDocument xdoc = XDocument.Load(path);
var elements = (
from doc in xdoc.Descendants("Unit")
where doc.Parent.Parent.Attribute("name").Value == _UnitTypeName &&
doc.Parent.Parent.Parent.Parent.Attribute("name").Value == _UnitCategoryN
doc.Parent.Parent.Parent.Parent.Parent.Parent.Attribute("name").Value ==
select doc
);
foreach (var element in elements)
{
Unit unit =
new Unit
{
Armour = _Armour,
Attacks = _Attacks,
BallisticSkill = _BallisticSkill,
Composition = _Composition,
DedicatedTransport = _DedicatedTransport,
Initiative = _Initiative,
Leadership = _Leadership,
Options = _Options,
SaveThrow = _SaveThrow,
SpecialRules = _SpecialRules,
Strength = _Strength,
Toughness = _Toughness,
UnitName = _UnitName,
Weapons = _Weapons,
WeaponSkill = _WeaponSkill,
Wounds = _Wounds,
Points = _Points
};
XmlSerializer serializer = new XmlSerializer(typeof(Unit));
using (var stream = new MemoryStream())
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(stream, unit, ns);
stream.Position = 0;
//using (XmlReader reader = XmlReader.Create(stream))
//{
// XElement xe = XElement.Load(reader);
XElement xe = XElement.Load(#"C:\Test\tempfile.xml"); // For some reason loading via MemoryStream messes with xml formatting
element.AddBeforeSelf(xe);
//}
}
break;
}
xdoc.Save(path);
This is the structure of the XML Document:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfArmy>
<Army name="Tyranid">
<unit-category>
<UnitCategory name="Troops">
<unit-type>
<UnitType name="Infantry">
<unit>
<Unit points="5" name="Hornmagant" composition="20" weapon-skill="3" ballistic-skill="100" strength="3" toughness="4" wounds="1" initiative="3" attacks="3" leadership="5" saving-throw="6+" armour="Chitin" weapons="Many" special-rules="None" dedicated-transport="No" options="8">
<Amount>0</Amount>
</Unit>
<Unit points="5" name="Termagant" composition="20" weapon-skill="3" ballistic-skill="100" strength="3" toughness="4" wounds="1" initiative="3" attacks="3" leadership="5" saving-throw="6+" armour="Chitin" weapons="Many" special-rules="None" dedicated-transport="No" options="8">
<Amount>0</Amount>
</Unit>
</unit>
</UnitType>
</unit-type>
</UnitCategory>
</unit-category>
</Army>
</ArrayOfArmy>
You can use compound from clauses, which is similar to using nested foreach loops:
var elements = (
from army in xdoc.Descendants("Army")
where army.Attribute("name").Value == _ArmyName
from unitCategory in army.Descendants("UnitCategory")
where unitCategory.Attribute("name").Value == _UnitCategoryName
from unitType in unitCategory.Descendants("UnitType")
where unitType.Attribute("name").Value == _UnitTypeName
from unit in unitType.Descendants("Unit")
select unit
);
Note: the method syntax equivalent is SelectMany().
i have one xml string like this
string stxml="<Status>Success</Status>";
I also creaated one xml document
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode rootNode = doc.CreateElement("StatusList");
doc.AppendChild(rootNode);
i need an output like this.
<StatusList>
<Status>Success</Status>
</StatusList>
How can i achieve this.if we using innerhtml,it will insert.But i want to insert xml string as a xmlnode itself
A very simple way to achieve what you are after is to use the often overlooked XmlDocumentFragment class:
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode rootNode = doc.CreateElement("StatusList");
doc.AppendChild(rootNode);
//Create a document fragment and load the xml into it
XmlDocumentFragment fragment = doc.CreateDocumentFragment();
fragment.InnerXml = stxml;
rootNode.AppendChild(fragment);
Using Linq to XML:
string stxml = "<Status>Success</Status>";
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("StatusList", XElement.Parse(stxml)));
You could instead use the XElement class:
string stxml = "<Status>Success</Status>";
var status = XElement.Parse(stxml);
var statusList = new XElement("StatusList", status);
var output = statusList.ToString(); // looks as you'd like
If you want to write the new statusList content to a file:
statusList.Save(#"C:\yourFile.xml", SaveOptions.None);
you ca try it using xmlwriter
using (XmlWriter writer = XmlWriter.Create("new.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("StatusList");
writer.WriteElementString("Status", "Success"); // <-- These are new
writer.WriteEndDocument();
}
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using System.ComponentModel;
public class MyClass
{
public static void RunSnippet()
{
XmlNode node = default(XmlNode);
if(node == null)
Console.WriteLine(bool.TrueString);
if(node != null)
Console.WriteLine(bool.FalseString);
XmlDocument doc = new XmlDocument();
node = doc.CreateNode (XmlNodeType.Element,"Query", string.Empty);
node.InnerXml=#"<Where><Eq><FieldRef Name=""{0}"" /><Value Type=""{1}"">{2}</Value></Eq></Where>";
string xmlData = ToXml<XmlNode>(node);
Console.WriteLine(xmlData);
XmlNode node1 = ConvertFromString(typeof(XmlNode), #"<Query><Where><Eq><FieldRef Name=""{0}"" /><Value Type=""{1}"">{2}</Value></Eq></Where></Query>") as XmlNode;
if(node1 == null)
Console.WriteLine(bool.FalseString);
if(node1 != null)
Console.WriteLine(bool.TrueString);
string xmlData1 = ToXml<XmlNode>(node1);
Console.WriteLine(xmlData1);
}
public static string ToXml<T>(T t)
{
string Ret = string.Empty;
XmlSerializer s = new XmlSerializer(typeof(T));
using (StringWriter Output = new StringWriter(new System.Text.StringBuilder()))
{
s.Serialize(Output, t);
Ret = Output.ToString();
}
return Ret;
}
public static object ConvertFromString(Type t, string sourceValue)
{
object convertedVal = null;
Type parameterType = t;
if (parameterType == null) parameterType = typeof(string);
try
{
// Type t = Type.GetType(sourceType, true);
TypeConverter converter = TypeDescriptor.GetConverter(parameterType);
if (converter != null && converter.CanConvertFrom(typeof(string)))
{
convertedVal = converter.ConvertFromString(sourceValue);
}
else
{
convertedVal = FromXml(sourceValue, parameterType);
}
}
catch { }
return convertedVal;
}
public static object FromXml(string Xml, Type t)
{
object obj;
XmlSerializer ser = new XmlSerializer(t);
using (StringReader stringReader = new StringReader(Xml))
{
using (System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stringReader))
{
obj = ser.Deserialize(xmlReader);
}
}
return obj;
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
From my experience it is always better to work with unique id's i suggest u look in that situation first and then come back to this page, and research/position my code for a try if u did not yet have a solution for it.
I just finished it on my side for my own project, i have modified abit to look more integrated for your project.
Good luck. Sorry for the late response ;-)
XmlDocument xDoc = new XmlDocument();
string Bingo = "Identification code";
xDoc.Load(pathFile);
XmlNodeList idList = xDoc.GetElementsByTagName("id");
XmlNodeList statusList = xDoc.GetElementsByTagName("Status");
for (int i = 0; i < idList.Count; i++)
{
StatusNode = "<Status>fail</Status>";
XmlDocumentFragment fragment = xDoc.CreateDocumentFragment();
fragment.InnerXml = StatusNode;
statusList[i].InnerXml = "";
statusList[i].AppendChild(fragment);
if (statusList[i].InnerText == Bingo)
{
StatusNode = "<Status>Succes!</Status>";
fragment.InnerXml = Status;
statusList[i].InnerXml = "";
statusList[i].AppendChild(fragment);
}
}
xDoc.Save(pathFile);