Hi all i am creating an application to generate an XML file dynamically. In this i would like to add schemalocation and XSI to the XML Root how can i do this. I would like to add the following
xmlns="http://www.irs.gov/efile"
xsi:SchemaLocation="http://www.irs.goc/efile ReturnData941.xsd"
and
xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance"
This is my sample XML code that was generated dynamically
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode returnData = doc.CreateElement("ReturnData");
XmlAttribute documnetCount = doc.CreateAttribute("documentCount"); // after this i would like to add that schema
returnData.Attributes.Append(documnetCount);
So that i should get my XML as follows
<?xml version="1.0" encoding="UTF-8"?>
<ReturnData documentCount="" xsi:SchemaLocation="http://www.irs.goc/efile ReturnData941.xsd" xmlns="http://www.irs.gov/efile" xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance" />
I think you just need add a attribute like
XmlAttribute attr = doc.CreateAttribute("xsi", "schemaLocation", " ");
attr.Value = "http://www.irs.goc/efile ReturnData941.xsd";
returnData.Attributes.Append(attr);
I wonder if this is the best way of approaching things? Many validation APIs allow you to specify the schema location and instance document location independently, and that's likely to be more efficient than storing the schema location within the instance.
Generally I'm sceptical about xsi:schemaLocation anyway. If you're validating the instance, that's often because you don't trust it, and if you don't trust it, why should you trust its xsi:schemaLocation?
Related
I am trying to change the values in a Farming simulator 22 savegame xml file from C# in visual studio. There are a lot of nodes so I have reduced them to make things easier. I want to know how to replace the value in the node using C# with out having to create and rebuild the xml file from scratch.
the path to the xml file is: (C:\Users\Name\Documents\My Games\FarmingSimulator2022\savegame1\careerSavegame.xml)
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<careerSavegame revision="2" valid="true">
<settings>
<savegameName>My game save</savegameName>
<creationDate>2022-05-03</creationDate>
<mapId>MapFR</mapId>
<mapTitle>Haut-Beyleron</mapTitle>
<saveDateFormatted>2022-08-22</saveDateFormatted>
<saveDate>2022-08-22</saveDate>
<resetVehicles>false</resetVehicles>
</careerSavegame>
You can use the System.Xml.Linq namespace to access the xml file. This will load the file in the memory.
There is one class inside it, XDocument, that represents the xml document.
String filePath = "C:\Users\Name\Documents\My Games\FarmingSimulator2022\savegame1\careerSavegame.xml"
XDocument xdoc = XDocument.Load(filePath);
var element = xdoc.Elements("MyXmlElement").Single();
element.Value = "foo";
xdoc.Save("file.xml");
You can set the element variable as per the one which is needed to be replaced.
Through some research I found the solution to editing the values within the nodes. In this example I only change the value of savegameName, but it will be the same for the rest.
//Routing the xml file
XmlDocument xmlsettings = new XmlDocument();
xmlsettings.Load(#"D:\careerSavegame.xml");
//Setting values to nodes through innertext
String FarmNameSetting = "Martek Farm";
XmlNode savegameNamenode =
xmlsettings.SelectSingleNode
("careerSavegame/settings/savegameName");
savegameNamenode.InnerText = FarmNameSetting;
I am trying to access the second element in this xml (google kml type) of file and the issue I am having is I get returned null values for my code unless I remove out the <kml xmlns="http://earth.google.com/kml/2.0"> and the related close from the source file. Here is the code I'm using. (mind you this works if I remove the specified line so what I'm looking for is a clean way to process this file without editing the supplied source file.)
XmlDocument doc = new XmlDocument();
doc.Load("2014_q2.xml");
XmlNodeList xnlNodes = doc.SelectNodes("/kml/Document/Folder");
var Node2Use = xnlNodes.Item(1);
here is the top of the source file:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.0">
<Document>
<open>1</open>
<Folder>
<name>Pts_2014_q3_point Drawing</name>
<Placemark>
<description>HOLTSVILLE</description>
<name>00501</name>
<Style>
<IconStyle>
<color>ffc0c0c0</color>
I have a break on the var Node2Use = xnlNodes.Item(1); line so I can see the contents and thats where I see that I have a zero value where I should have 2 for Folder (like mentioned I get the 2 when I remove out that kml tagged line.)
You need to include the namespace. Something like this:
XmlDocument doc = new XmlDocument();
doc.Load("2014_q2.xml");
XNamespace ns = "http://earth.google.com/kml/2.0";
XmlNodeList xnlNodes = doc.SelectNodes(ns + "/kml/Document/Folder");
Here's the XML:
<PolicyChangeSet schemaVersion="2.1" username="" description="">
<Attachment name="" contentType="">
<Description/>
<Location></Location>
</Attachment>
</PolicyChangeSet>
I'm just trying to add the value "XXX" between the "location" tag.
I tried this but it isn't working:
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppVars.pxCentralXMLPayloadFilePath);
node = xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachment/location");
node.InnerText = "XXX";
xmlDoc.Save(AppVars.pxCentralXMLPayloadFilePath);
What am I missing?!
doc.Save(#"XML FILE PATH"); //This will save the changes to the file.
Please use iteration through ChildNodes of XmlDocument - as described in walkthrough from MS Support site. According to documentation of SelectSingleNode() method:
The XmlNode should not be expected to be connected "live" to the XML
document. That is, changes that appear in the XML document may not
appear in the XmlNode, and vice versa.
Found out what the problem was CASE SENSITIVITY.
I am trying to select all the child nodes of root node of an xml document using XPath query.
My xml file looks something like following :
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<automotive_industry>
<automotive />
<rail_global_services />
</automotive_industry>
</root>
AND
<?xml version="1.0" encoding="UTF-8" ?>
<root xmlns="http://www.my_department.my_company.com/project_name">
<automotive_industry>
<automotive />
<rail_global_services />
</automotive_industry>
</root>
C# Code to select root node is as follows :
XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNodeList allNodes = gazetteDocument.SelectNodes("root");
This code works fine, it selects all the child nodes of root node when root node does not have any attribute that is, it works for 1st xml file but does not work for 2nd xml file because 2nd file has xmlns attribute.
Does anyone knows how to select all the child nodes of root node when root node has attributes??
EDIT :
I found one XPath query : /* This query selects root node no matter whether it has any attribute or not. Once root node is selected, I can iterate through its all the child nodes .
Although the namespace in your XML document is fine, you need to use it in your SelectNodes.
Use this code for your second XML:
XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(gazetteDocument.NameTable);
nsmgr.AddNamespace("ns", "http://www.my_department.my_company.com/project_name");
XmlNodeList allNodes = gazetteDocument.SelectNodes("ns:root", nsmgr);
The better way would be to use XDocument and corresponding classes. They are a lot easier to work with.
I don't know the old xml methods of C#, but you could always open the file to read as normal text, and then read to the first node and parse it however you like.
You can use GetElementsByTagName method below are the snippet of my code
XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNodeList allNodes = gazetteDocument.GetElementsByTagName("root");
I'm using the following code to initialise an XmlDocument
XmlDocument moDocument = new XmlDocument();
moDocument.AppendChild(moDocument.CreateXmlDeclaration("1.0", "UTF-8", null));
moDocument.AppendChild(moDocument.CreateElement("kml", "http://www.opengis.net/kml/2.2"));
Later in the process I write some values to it using the following code
using (XmlWriter oWriter = oDocument.DocumentElement.CreateNavigator().AppendChild())
{
oWriter.WriteStartElement("Placemark");
//....
oWriter.WriteEndElement();
oWriter.Flush();
}
This ends up giving me the following xml when I save the document
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark xmlns="">
<!-- -->
</Placemark>
</kml>
How can I get rid of the empty xmlns on the Placemark element?
--EDITED TO SHOW CHANGE TO HOW PLACEMARK WAS BEING WRITTEN--
If I put the namespace in the write of placemark then non of the elements are added to the document.
I have fixed the issue by creating the document with the following code (no namespace in the document element)
XmlDocument moDocument = new XmlDocument();
moDocument.AppendChild(moDocument.CreateXmlDeclaration("1.0", "UTF-8", null));
moDocument.AppendChild(moDocument.CreateElement("kml"));
And by saving it with the following code to set the namespace before the save
moDocument.DocumentElement.SetAttribute("xmlns", msNamespace);
moDocument.Save(msFilePath);
This is valid as the namespce is only required in the saved xml file.
This is an old post, but just to prevent future bad practice; you should never declare the xmlns namespace in an XML document, so this may be the cause why you get empty nodes since you are doing something the XmlDocument is not supposed to do.
The prefix xmlns is used only to declare namespace bindings and is by
definition bound to the namespace name http://www.w3.org/2000/xmlns/.
It MUST NOT be declared . Other prefixes MUST NOT be bound to this
namespace name, and it MUST NOT be declared as the default namespace.
Element names MUST NOT have the prefix xmlns.
Source: http://www.w3.org/TR/REC-xml-names/#ns-decl
The following code worked for me (source):
XmlSerializer s = new XmlSerializer(objectToSerialize.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
s.Serialize(xmlWriter, objectToSerialize, ns);
oWriter.WriteStartElement("Placemark"); should work, because the parent node already has the right namespace.
Did you try:
oWriter.WriteStartElement("kml", "Placemark", "kml");
You needed
oWriter.WriteStartElement("Placemark", "http://www.opengis.net/kml/2.2");
otherwise the Placemark element gets put in the null namespace, which is why the xmlns="" attribute is added when you serialize the XML.