I have problem parse XML in C# because XML not have root element.
How can I add root element? When try XDocument show erorrs about root element.
Maybe can use some file stream?
Example:
<data>
<datetime>29.06.2020 10:15:15</datetime>
<Lenght/>
<Width>3</Width>
<Height>2</Height>
</data>
<data>
<datetime>29.06.2020 10:15:01</datetime>
<Lenght>1</Lenght>
<Width>2</Width>
<Height>3</Height>
</data>
My code:
XmlDocument report = new XmlDocument();
report.Load(fileOfReport); //there show error about root element
XmlElement root = report.CreateElement("root");
var items = report.GetElementsByTagName("data");
for (int i = 0; i < items.Count; i++)
{
root.AppendChild(items[i]);
}
report.AppendChild(root);
report.SaveAs(fileOfReport);
You can try the following solution.
Lots of minutiae string handling, but seems to be working for your case. XmlNodeType enumerator has 18 entries total. Your XML is relatively simple, that's why the switch has just 3 node types in the code. You can use StringBuilder instead of string data type while composing a well-formed XML.
void Main()
{
const string FILENAME = #"e:\temp\NoRootFile.xml";
const string NEWFILENAME = #"e:\temp\NoRootFileFixed.xml";
string xmlString = "<root>";
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader xr = XmlReader.Create(FILENAME, settings))
{
while (xr.Read())
{
if (xr.NodeType != XmlNodeType.XmlDeclaration)
{
switch (xr.NodeType)
{
case XmlNodeType.Element:
xmlString += "<" + xr.Name + ((xr.IsEmptyElement) ? "/>" : ">");
break;
case XmlNodeType.Text:
xmlString += xr.Value;
break;
case XmlNodeType.EndElement:
xmlString += "</" + xr.Name + ">";
break;
}
}
}
}
xmlString += "</root>";
XDocument xdoc = XDocument.Parse(xmlString);
xdoc.Save(NEWFILENAME);
}
Related
I have a problem with saving data from XML URL nodes, using XMLReader, to a text file. Can you please help me out? I don't know how to do it.
Here is the code:
namespace XMLdemo2
{
class Program
{
static void Main(string[] args)
{
// Start with XmlReader object
String URLString = "https://www.shortcut.lv/xmls/tiesraide/ltv1.xml";
XmlTextReader reader = new XmlTextReader(URLString);
{
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name.ToString())
{
case "auth_token":
Console.WriteLine("Tokens IR : " + reader.ReadString());
break;
}
//Console.WriteLine("");
}
}
Console.ReadKey();
}
}
}
}
You can try something easier like this (if it's only one line you want to read)
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("https://www.shortcut.lv/xmls/tiesraide/ltv1.xml");
XmlNode authTokenNode = xmlDoc.SelectSingleNode("//auth_token");
if(authTokenNode != null)
Console.WriteLine(authTokenNode.InnerText);
If it is multiple lines
XmlDocument xmlDoc = new XmlDocument();
XmlNodeList itemNodes = xmlDoc.SelectNodes("//auth_token");
foreach(XmlNode itemNode in itemNodes)
{
if((itemNode != null)
Console.WriteLine(itemNode.InnerText);
}
I am trying to retrieve all elements from an XML file, but I just can reach one, is there any way I can retrieve all?
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (XmlReader reader = XmlReader.Create(new StreamReader(objResponse.GetResponseStream())))
{
while (reader.Read())
{
#region Get Credit Score
//if (reader.ReadToDescendant("results"))
if (reader.ReadToDescendant("ssnMatchIndicator"))
{
string ssnMatchIndicator = reader.Value;
}
if (reader.ReadToDescendant("fileHitIndicator"))
{
reader.Read();//this moves reader to next node which is text
result = reader.Value; //this might give value than
Res.Response = true;
Res.SocialSecurityScore = result.ToString();
//break;
}
else
{
Res.Response = false;
Res.SocialSecurityScore = "Your credit score might not be available. Please contact support";
}
#endregion
#region Get fileHitIndicator
if (reader.ReadToDescendant("fileHitIndicator"))
{
reader.Read();
Res.fileHitIndicator = reader.Value;
//break;
}
#endregion
}
}
Can somebody help me out with this issue?
I am also using objResponse.GetResponseStream() because the XML comes from a response from server.
Thanks a lot in advance.
Try this :
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode ;
int i = 0;
string str = null;
FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("Product");
for (i = 0; i <= xmlnode.Count - 1; i++)
{
xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
MessageBox.Show (str);
}
I don't know why what you're doing is not working, but I wouldn't use that method. I've found the following to work well. Whether you're getting the xml from a stream, just put it into a string and bang...
StreamReader reader = new StreamReader(sourcepath);
string xml = reader.ReadToEnd();
reader.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList list = doc.GetElementsByTagName("*");
foreach (XmlNode nd in list)
{
switch (nd.Name)
{
case "ContactID":
var ContactIdent = nd.InnerText;
break;
case "ContactName":
var ContactName = nd.InnerText;
break;
}
}
To capture what is between the Xml tags, if there are no child Xml tags, use the InnerText property, e.g. XmlNode.InnerText. To capture what is between the quotes in the nodes' attributes, use XmlAttribute.Value.
As for iterating through the attributes, if one of your nodes has attributes, such as the elements "Name", "SpectralType" and "Orbit" in the Xml here:
<System>
<Star Name="Epsilon Eridani" SpectralType="K2v">
<Planets>
<Planet Orbit="1">Bill</Planet>
<Planet Orbit="2">Moira</Planet>
</Planets>
</Star>
</System>
Detect them using the Attributes property, and iterate through them as shown:
if (nd.Attributes.Count > 0)
{
XmlAttributeCollection coll = nd.Attributes;
foreach (XmlAttribute cn in coll)
{
switch (cn.Name)
{
case "Name":
thisStar.Name = cn.Value;
break;
case "SpectralType":
thisStar.SpectralClass = cn.Value;
break;
}
}
}
You might find some more useful information HERE.
I have an XML file with nodes and data...I need to write that into a text file as normal data. The nodes being the headers of the data
that follow.
EG XML:
<Bank>
<accountholder>Georgina Wax</accountholder>
<accountnumber>408999703657</accountnumber>
<accounttype>cheque</accounttype>
<bankname>National Bank</bankname>
<branch>Africa</branch>
<amount>2750.00</amount>
<date>12/01/2012</date>
</Bank>
To txt file and formatted as :
accountholder accountnumber accounttype bankname
Georgina Wax 408999703657 cheque National Bank
I can't seem to have it to have spaces between the data and hearders.
Below is what I tried :
StreamWriter writer = File.CreateText(#"C:\\Test.txt");
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\\bank.xml");
writer.WriteLine(string.Join("|",doc.SelectSingleNode("/debitorders/deduction").ChildNodes.C ast<XmlElement>().Select(e => doc.SelectSingleNode("/debitorders/deduction/bankname").ToString())));
foreach (XmlElement book in doc.SelectNodes("/debitorders/deduction"))
{
writer.WriteLine(book.ChildNodes.Cast<XmlElement>().Select(e => e.InnerText).ToArray());
}
Please help.
This will produce output like you want.
private static void LoadAndWriteXML()
{
string headerFiles = "";
string values = "";
using (XmlReader reader = XmlReader.Create(#"C:\\bank.xml"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && !reader.Name.Equals("Bank")) // we have to skip root node means bank node.
{
headerFiles += reader.Name + " ";
values += reader.ReadString() + " ";
}
}
}
StreamWriter writer = new StreamWriter(#"C:\\Test.txt");
writer.WriteLine(headerFiles.Trim());
writer.WriteLine(values.Trim());
writer.Close();
}
XDocument xdoc = new XDocument();
xdoc = XDocument.Load(fname);
xdoc.Save(fname1);
will save the file with the tags alignment formating
I want to read an XML file and match tag </contrib-group> and write a string after this tag
string Final = File.ReadAllText(Npath);
string Oxml = path + "\\" + Oword + ".abs.xml";
if (File.Exists(Oxml))
{
StreamReader xml = new StreamReader(Oxml,Encoding.UTF8);
string xmltag = xml.ReadToEnd();
//File.OpenWrite(Oxml);
xml.Close();
StreamWriter write = new StreamWriter(Oxml, true, Encoding.UTF8);
Match tag = Regex.Match(xmltag, #"</contrib-group>");
if (tag.Success == true)
{
write.WriteLine(Environment.NewLine);
write.Write(Final);
}
}
So I need to write the string Final to the XML file called Oxml after the matched XML tag </contrib-group>
If you are willing to save the new content as a valid XML file which you can work with, you should use the XML classes for that approach, this should look like this (untested):
XmlDocument doc = new XmlDocument();
doc.Load("YourFile.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("contrib-group");
for (int i=0; i < elemList.Count; i++)
{
XmlNode xnode = elemList[i];
XmlNode xnodeParent = xnode.ParentNode;
XMLNode newNode = doc.CreateNode(XmlNodeType.Element, "NodeName", "");
newNode.InnerText = "ContentInsideTheNode";
xnodeParent.InsertAfter(newNode, xnode);
}
doc.Save("YourFile.xml");
If you only need to replace the string for other purposes than saving it where having a valid XML is not an issue you can just handle it as a string and use the String.Replace (String, String) Method
string searchedTag = #"</contrib-group>";
string tagAndNewContent = #"</contrib-group>" + newContent;
string fileContentString = File.ReadAllText("YourFile.xml");
string ouput = fileContentString.Replace(searchedTag, tagAndNewContent);
I'm having program like below. The concept is Read XML value from URL, but my program read the xml structure only, not the code datas. Like <Billing Address></Billing Address>... etc only. But the original XML value is <Billing Address>Strre1</Billing Address>. The Program does not read the inside value.
public static void zohoCRMReadAccounts()
{
var val = auth();
var val1= val[0];
var val2= val[1];
String xmlURL = "URL";
XmlTextReader xmlReader = new XmlTextReader(xmlURL);
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + xmlReader.Name);
// Read the attributes:
while (xmlReader.MoveToNextAttribute())
Console.Write(" " + xmlReader.Name + "=’"
+ xmlReader.Value + "’");
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine(xmlReader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + xmlReader.Name);
Console.WriteLine(">");
break;
}
}
Console.WriteLine("Press any key to continue…");
Console.ReadLine(); //Pause
}
Please help me to fix
XML Elements cannot have spaces in their names. Try to remove them first
First download the XML. Then Use like,
try {
//read xml
XmlDocument xdoc = new XmlDocument();
xdoc.Load("XMLFilePath");
XmlNodeList nodes = xdoc.SelectNodes(#"rss/channel/item");
foreach (XmlNode node in nodes)
{
XmlNode titleNode = node.SelectSingleNode("title");
string title = titleNode == null ? string.Empty : titleNode.InnerText;
};
}