why XElement cannot save my xml file to the file? - c#

I want to construct a long xml string and some of its entities are from another xml file read by a dll. In the end, I'd like to save this xml string to a file by XElement.Save(). It cannot save the string to the file.
For example:
XElement root = new XElement("Root");
// .....
root.Save(filename); // <-- wrong!
However, If I do not use the dll, everything is fine. Even I just call the dll and do nothing else, it won't work for me. Can anybody help me? Thanks

For Appending Node into existing XML File:
From beginning,
1) Create one Root.xml file:
<?xml version="1.0" encoding="utf-8"?>
<Main>
</Main>
2) Use this code to Load and Append Nodes:
XElement xml = new XElement("Root");
XDocument xdoc = XDocument.Load("Root.xml");
xdoc.Element("Main").Nodes().Last().AddAfterSelf(xml); //append after the last backup element
xdoc.Save("Root.xml");

Related

How to C# Reading xml file

I have an XML file. I want C # with the desktop application. There are similar solutions on the site. But I can't read with the XML I have. How should I proceed about this?
<?xml version="1.0"?>
<RealTimeMetrics SiteId="Site ID">
<Properties>
<Version>3</Version>
<TransmitTime>1581582053</TransmitTime>
<MacAddress>00:b0:9d:23:72:f0</MacAddress>
<IpAddress>192.168.1.99</IpAddress>
<HostName>Cam-19100400</HostName>
<HttpPort>80</HttpPort>
<HttpsPort>443</HttpsPort>
<Timezone>3</Timezone>
<TimezoneName>(GMT 03:00) Nairobi</TimezoneName>
<DST>0</DST>
<HwPlatform>2500</HwPlatform>
<SerialNumber>19100400</SerialNumber>
<DeviceType>0</DeviceType>
<SwRelease>4.1.4005.2249</SwRelease>
</Properties>
<RTReport Date="2020-02-13T11:20:53">
<RTObject Id="0" DeviceId="Demo" Devicename="Demo" ObjectType="0" Name="TEST">
<RTCount TotalEnters="0" TotalExits="0"/>
</RTObject>
</RTReport>
</RealTimeMetrics>
I used simple solution to read and edit XML file:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("path\to\file.xml");
XmlNode node = xmlDoc.SelectSingleNode("//nodeName");
node.InnerText = value;
xmlDoc.Save("path\to\file.xml");
You can load this file, read single node or all nodes, change value of InnerText or Add Atributes, end save this file

C# Skip anything to next tag

I have a log file in xml format like
<log> // skip this node
<?xml version="1.0" encoding="UTF-8"?>
<qbean logger="main-logger">
</qbean>
</log>
<log> // go to this node
</log>
Now ReadToNextSibling("log") throw an exception an I need to skip content of first "log" tag and move to next "log" tag without throwing exception.
Is there a way?
Hint:
Your XML is invalid since the <?xml version="1.0" encoding="UTF-8"?> has to be before the root element. You can search for it and remove it if that fixes your problem. You can use yourXml.Repalce("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "")
You have to create a root element for your XML to be valid for parsing.
Then, you can use the XmlDocument class to parse the XML data that you have and skip anything you want. You would need something like this:
var document = new XmlDocument();
document.LoadXml(yourXml);
document.DocumentElement.ChildNodes[1]

How to change the data within elements in a XML file using C#?

I'm kind of new to XML files in C# ASP.NET. I have a XML in the below format:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Installation>
<ServerIP>192.168.20.110</ServerIP>
<DB_Name>USTCKT1</DB_Name>
<Username>jorame</Username>
<Password>Cru$%e20</Password>
<Table_PreFix>TCK</Table_PreFix>
</Installation>
I need to change the values within each element. For example, when an user clicks I should be able to replace 192.168.20.110 with 192.168.1.12.
How can I accomplish this? Any help will be really appreciated.
You should look at using the methods in the XDocument class. http://msdn.microsoft.com/en-us/library/bb301598.aspx
Specifically look at the methods: Load(string) - to load an XML file, Element() - to access a specific element and Save(string) - to save the XML document. The page on Element() has some sample code which can help.
http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx
You can do something like this using the XDocument class:
XDocument doc = XDocument.Load(file.xml);
doc.Element("Installation").Element("ServerIP").Value = "192.168.1.12";
//Update the rest of the elements
doc.Save(file.xml);
More Details
If you run into namespace issues when selecting your elements you will need to include the xml namespace in the XElement selectors eg doc.Element(namspace + "Installation")
In general, you can do it in the following steps:
Create a new XmlDocument object and load the content. The content might be a file or string.
Find the element that you want to modify. If the structure of your xml file is too complex, you can use xpath you find what you want.
Apply your modification to that element.
Update your xml file.
Here is a simple demo:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("file.xml"); // use LoadXml(string xml) to load xml string
string path = "/Installation/ServerIP";
XmlNode node = xmlDoc.SelectSingleNode(path); // use xpath to find a node
node.InnerText = "192.168.1.12"; // update node, replace the inner text
xmlDoc.Save("file.xml"); // save updated content
Hope it's helpful.

how Deserializing this type of xml file?

<row>
<id>1</id>
<code></code>
<name></name>
<address></address>
<state></state>
<zone>?</zone>
</row>
<row>
<id>2</id>
<code>AA</code>
<name>Ataria</name>
<address>Sitapur National Highway 24, Uttar Pradesh</address>
<state>Uttar Pradesh</state>
<zone>NER</zone>
</row>
i have no root element in this xml file only row element start and end this xml file.
how Deserializing this type of data ? in c#
If you sure that missing root is only the one issue with your XML - just add it manually:
string fileContent = File.ReadAllText(path);
string rawXml = "<root>" + fileContent + "</root>";
// now you can use LINQ-to-XML or whatever
XDocument xdoc = XDocument.Load(rawXml);
You can also load an XML Fragment directly, via
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create("tracelog.xml", settings))
{
while (reader.Read())
{
// Process each node of the fragment,
// possibly using reader.ReadSubtree()
}
}
You would create XElements by passing the results of reader.ReadSubTree() to XElement.Load(...).
Well to start with, it's not an XML file - or at least, it doesn't represent an XML document.
One option would be to copy the file into a new file which does have document start/end tags... then you can load it as a normal document. Just create a file, write a document start tag, copy the contents of this file, then write a document end tag, and close the file handle. You could even do this in memory.
Alternatively, it may be possible to read it as it is, in fragments - possibly via XmlReader. I can't say it's something I've done, and I'd generally encourage you to create a full XML file instead, as then you'll be on more familiar territory.
its not an XML file if it doesn't have the root. parser will throw an error if you try to parse it. you can do this way
<?xml version="1.0"?>
<Root>
--- add your file content here
</Root>
then give this file path to the parser.

How can I correct the code to read a xml file?

This code works as it is but when I reference an external xml file in doc.Loadxml, it stops working. How can I get it to work? I don't quite understand.
I use this to call GetXmlData and provide source for the gridview :GridView1.ItemsSource = GetXmlData();
private static object GetXmlData()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(#"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Products>
<Product>
<ID>1</ID>
<Name>ASP.NET</Name>
</Product>
</Products>
");
XmlDataProvider provider = new XmlDataProvider();
provider.IsAsynchronous = false;
provider.Document = doc;
provider.XPath = "Products/Product";
return new ObservableCollection<XmlNode>((IEnumerable<XmlNode>)provider.Data);
}
You need
doc.Load(fileName);
instead of
doc.LoadXml(xml);
XMLDocument has several Load methods, see them with their description:
Load(Stream) Loads the XML document from the specified stream.
Load(String) Loads the XML document from the specified URL.
Load(TextReader) Loads the XML document from the specified TextReader.
Load(XmlReader) Loads the XML document from the specified XmlReader.
LoadXml(string) Loads the XML document from the specified string.
You're using the last one which is as described used to load XML from a string.
Since you need to load the XML from a file, so you've to use to Load method, as opposed to LoadXml. I think second method is better suited for your situation. You can pass the fullpath of the XML file.
This should help you:
XmlDocument doc = new XmlDocument();
doc.Load(file_path);
The method you are calling only loads xml from a string. You need to read it from a file which requires a different method.

Categories