I am trying to create an XML string but the expected output is different from this code
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("Employee");
xml.AppendChild(root);
for (int i = 1; i < datacount; i++)
{
XmlElement child = xml.CreateElement("EmployeeName");
child.SetAttribute("value", "Name1");
root.AppendChild(child);
}
string xmlString = xml.OuterXml;
Expected output:
<?xml version="1.0" encoding="utf-8" ?>
<Employee>
<EmployeeName>Name1</EmployeeName>
<EmployeeName>Name2</EmployeeName>
</Employee>
Current output:
<?xml version="1.0" encoding="utf-8" ?>
<Employee>
<EmployeeName Value = "Name1" />
<EmployeeName Value = "Name1" />
</Employee>
XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("Employee");
xml.AppendChild(root);
//Create a new node and add it to the document.
//The text node is the content of the price element.
for (int i = 1; i < datacount; i++)
{
XmlElement elem = xml.CreateElement("EmployeeName");
XmlText text = xml.CreateTextNode("Name");
xml.DocumentElement.AppendChild(elem);
xml.DocumentElement.LastChild.AppendChild(text);
}
string xmlString = xml.OuterXml;
or you can use
child.InnerText="Name1";
Related
I am creating a xml document using the following C# code:
XmlDocument finalDoc = new XmlDocument();
//(1) the xml declaration is recommended, but not mandatory
XmlDeclaration xmlDeclaration = finalDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = finalDoc.DocumentElement;
finalDoc.InsertBefore(xmlDeclaration, root);
//(2) string.Empty makes cleaner code
XmlElement element1 = finalDoc.CreateElement(string.Empty, "root", string.Empty);
finalDoc.AppendChild(element1);
for (int i = 0; i < 5; i++)
{
XmlElement element2 = finalDoc.CreateElement(string.Empty,"song", string.Empty);
element2.SetAttribute("title", "title" + i);
element1.AppendChild(element2);
for (int k=0; k<5;k++)
{
XmlElement element3 = finalDoc.CreateElement(string.Empty, "line", string.Empty);
element3.InnerText = "text " + k;
element2.AppendChild(element3);
}
element1.AppendChild(element2);
}
finalDoc.Save("C:\\Users\\adm\\Downloads\\finalDoc.xml");
and I am getting the following output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<song title="title 0" />
<song title="title 0">
<line>text 0</line>
<line>text 1</line>
<line>text 2</line>
<line>text 3</line>
<line>text 4</line>
</song>
<song title="title 1" />
<song title="title 1">
...
</song>
...
</root>
As you can see, I am having a duplicated empty "song" node for some reason, what am I missing here?
I don't see anything out of order here, could someone please help, thanks in advance.
You AppendChild 2 times element2. Remove first one
for (int i = 0; i < 5; i++)
{
XmlElement element2 = finalDoc.CreateElement(string.Empty,"song", string.Empty);
element2.SetAttribute("title", "title" + i);
for (int k=0; k<5;k++)
{
XmlElement element3 = finalDoc.CreateElement(string.Empty, "line", string.Empty);
element3.InnerText = "text " + k;
element2.AppendChild(element3);
}
element1.AppendChild(element2);
}
The line element1.AppendChild(element2); occurs twice in your for loop, third and last line in the loop.
Is it possible to include a complete XmlDocument in a SOAP Envelope?
I have tried countless methods which caused a 500 Server Error when including the XML definition from the dataFile so have included a RemoveXmlDefinition to deal with that, now I am getting a 400 Bad Request Error.
No matter what I try, I end up with XML with formatting included in the final SOAP Envelope, I just need a string.
public string RemoveXmlDefinition(string xmlDocumentInnerXml)
{
var xDocument = XDocument.Parse(xmlDocumentInnerXml);
xDocument.Declaration = null;
var regex = new Regex(#">\s*<");
return regex.Replace(xDocument.ToString(), "><");
}
var dataFile = System.Web.HttpContext.Current.Server.MapPath("\\XML\\Test.xml");
var debug = "File Name = " + dataFile + "<br />";
var xmlDocument = new XmlDocument();
try
{
xmlDocument.XmlResolver = null;
xmlDocument.PreserveWhitespace = false;
xmlDocument.Load(dataFile);
}
catch (XmlException xmlException)
{
var test = xmlException.Message;
debug = debug + "Error Code = " + xmlException.GetHashCode() + "<br />";
debug = debug + "Error Reason = " + xmlException.InnerException + "<br />";
debug = debug + "Error Line = " + xmlException.LineNumber + "<br />";
}
var soapfile = Server.MapPath("/XML/Soap.xml");
if (System.IO.File.Exists(soapfile))
{
System.IO.File.Delete(soapfile);
}
var xmlTextWriter = new XmlTextWriter(dataFile, Encoding.UTF8) {Formatting = Formatting.None};
xmlDocument.Save(xmlTextWriter);
xmlTextWriter.Close();
string xmlDocumentInnerXml = RemoveXmlDefinition(xmlDocument.InnerXml);
using (var writer = new XmlTextWriter(soapfile, Encoding.UTF8) { Formatting = Formatting.Indented })
{
writer.WriteStartDocument();
writer.WriteStartElement("soap", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
writer.WriteStartElement("soap", "Body", null);
writer.WriteStartElement("XmlString");
writer.WriteAttributeString("xmlns", "http://tempuri.org/");
writer.WriteFullElementString("xmlDocumentInnerXml", xmlDocumentInnerXml);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
xmlDocumentInnerXml
<Affiliate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" leadnumber="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id=""><Details><Amount></Amount><Forename></Forename><Surname></Surname><Tel></Tel><Email></Email></Details></Affiliate>
soapEnvelope
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<XmlString xmlns="http://tempuri.org/">
<xmlDocumentInnerXml>
<Affiliate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" leadnumber="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="">
<Details>
<Amount />
<Forename />
<Surname />
<Tel />
<Email />
</Details>
</Affiliate>
</xmlDocumentInnerXml>
</XmlString>
</soap:Body>
</soap:Envelope>
I have listed the sample SOAP 1.1 request XmlString is expecting below:
XmlString
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<XmlString xmlns="http://tempuri.org/">
<xmlDocumentInnerXml>string</xmlDocumentInnerXml>
</DmAppString>
</soap:Body>
</soap:Envelope>
Any assistance would be much appreciated.
I suspect that the reason for the errors is that you write the XML directly into the xmlDocumentInnerXml in the WriteFullElementString-method by using the WriteRaw-method:
public static void WriteFullElementString(this XmlTextWriter writer, string localName, string value)
{
writer.WriteStartElement(localName);
writer.WriteRaw(value);
writer.WriteFullEndElement();
}
This might lead to some schema validation errors. In order to include the XML string as a CData-block and thereby encode it correctly, you can use the WriteCData-method instead of WriteRaw:
public static void WriteFullElementString(this XmlTextWriter writer, string localName, string value)
{
writer.WriteStartElement(localName);
writer.WriteCData(value);
writer.WriteFullEndElement();
}
XmlDocument objXmldoc = new XmlDocument();
objXmldoc.Load(txtBrowseFilePath.Text);
XmlNodeList objxmlNodeList=null;
objxmlNodeList = objXmldoc.SelectNodes(#"/AppXmlLogWritter/LogData[LogDateTime/text()[starts-with(. , '" + dateTimePickerFromDate.Value.ToString("yyyyMMdd") + "')]]");
DataSet ds = new DataSet();
ds.ReadXml(objxmlNodeList);
How to convert XmlNodeList to Xmlstring to bind xml data with dataset
xml file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<AppXmlLogWritter>
<LogData>
<LogID>5678201301161640382918</LogID>
<LogDateTime>20130116164037</LogDateTime>
<LogType>Message</LogType>
<LogFlag>RISLogFlag</LogFlag>
<LogApplication>BaburaoLogApplication</LogApplication>
<LogModule>RISLogModule</LogModule>
<LogLocation>RISLogLocation</LogLocation>
<LogText>BaburaoLogText</LogText>
</LogData>
<LogData>
<LogID>5678201301161640382919</LogID>
<LogDateTime>20130116164038</LogDateTime>
<LogType>Warning</LogType>
<LogFlag>MACLogFlag</LogFlag>
<LogApplication>MACLogApplication</LogApplication>
<LogModule>MACLogModule</LogModule>
<LogLocation>MACLogLocation</LogLocation>
<LogText>MACLogText</LogText>
</LogData>
</AppXmlLogWritter>
try such a function:
private string XmlNodeListToString(XmlNodeList nodeList)
{
String returnStr = "";
if (nodeList != null)
{
foreach (XmlNode node in nodeList)
{
returnStr += node.OuterXml;
}
}
/*
//I think this is not needed from Dataset.ReadXml
returnStr = returnStr .Replace("&", "&");
returnStr = returnStr.Replace("<", "<");
returnStr = returnStr.Replace(">", ">");
returnStr = returnStr.Replace("'", "'");
returnStr = returnStr.Replace("\"", """);
*/
return "<Root>"+returnStr+"</Root>";
}
Also from your comments seems that you have a long file name issue.
try objXmldoc.Load(#txtBrowseFilePath.Text);
or if it does not succeed
try something else like preceding filepath with \\?\ as i found out in this link
For example, "\\?\D:\very long path".
I am trying to get the attribute values of all nodes with the tag name "Event" into a comboBox on a WindowsForm. I have tried this code below, however, nothing populates in the comboBox.
if (selectEventComboBox.SelectedIndex != -1)
{
string filePath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
+ "\\" + selectFileComboBox.SelectedItem.ToString()
+ "dogs.xml";
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNodeList eventList = doc.GetElementsByTagName("Event");
for (int count = 0; count < eventList.Count; count++)
{
selectEventComboBox.Items.Add(eventList[count].Attributes.ToString());
}
}
This works fine
XmlDocument doc = new XmlDocument();
doc.Load("myxml.xml");
XmlNode root = doc.DocumentElement;
XmlNodeList nodeList = root.SelectNodes("//Event");
for (int i = 0; i < nodeList.Count; i++)
{
Console.WriteLine("row: {0}, InnerText: {1}, ID: {2}",i, nodeList[i].InnerText, nodeList[i].Attributes["id"].Value);
}
Contents of myxml.xml
<?xml version="1.0" encoding="utf-8" ?>
<root>
<Event id="1">Event one</Event>
<Event id="2">Event two</Event>
<Event id="3">Event three</Event>
<Event id="4">Event four</Event>
</root>
I need to get a value out of an XML file...
I have this XML file for example:
<?xml version="1.0"?>
<hwids>
<user>
<userName>Ivar</userName>
<hwid>BFEB-FBFF-0000-06FD-C87C-FA30</hwid>
</user>
<user>
<userName>Jerremy</userName>
<hwid>BFE9-FBFF-0000-06E8-E41E-5034</hwid>
</user>
</hwids>
Now, if I have the value BFEB-FBFF-0000-06FD-C87C-FA30, how do I get the name Ivar, out of the xml file trough C#?
I used in my application something like this:
using System.Data;
DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFullPath, XmlReadMode.Auto);
DataRow[] dataRows = dataSet.Tables["user"].Select("hwid like 'BFEB-FBFF-0000-06FD-C87C-FA30'");
if (dataRows.Length == 0)
return;
string sUser = dataRows[0]["userName"].ToString();
you can accomplish this also with XmlDocument of the System.Xml namespace, which is supported in .NET 3.0
var xml = "<?xml version=\"1.0\"?>" +
"<hwids> " + "<user>" +
"<userName>Ivar</userName>" +
"<hwid>BFEB-FBFF-0000-06FD-C87C-FA30</hwid>"+
"</user> " +
"<user>" +
"<userName>Jerremy</userName>" +
"<hwid>BFE9-FBFF-0000-06E8-E41E-5034</hwid>" +
"</user>" +
"</hwids>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var ret = doc.GetElementsByTagName("userName");
for (int i = 0; i < ret.Count; i++)
{
Debug.WriteLine(ret.Item(i).InnerText);
}
I think this should work:
XElement root = XElement.Load("file.xml");
IEnumerable<XElement> hws =
from el in root.Elements("user")
where (string)el.Element("userName") == "Ivar"
select el.Descendant("hwid);
Haven't tested it out.