I want to create a xml document and root element like this:
<rdf:RDF xmlns:cim="http://iec.ch/TC57/2009/CIM-schema-cim14#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
I try create this like that:
XmlDocument doc = new XmlDocument();
XmlNode rootNode = doc.CreateElement("rdf:RDF xmlns:cim="http://iec.ch/TC57/2009/CIM-schema-cim14#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">");
doc.AppendChild(rootNode);
XmlNode userNode = doc.CreateElement("user");
XmlAttribute attribute = doc.CreateAttribute("age");
attribute.Value = "42";
userNode.Attributes.Append(attribute);
userNode.InnerText = "John Doe";
rootNode.AppendChild(userNode);
userNode = doc.CreateElement("user");
attribute = doc.CreateAttribute("age");
attribute.Value = "39";
userNode.Attributes.Append(attribute);
userNode.InnerText = "Jane Doe";
rootNode.AppendChild(userNode);
doc.Save("C:/xml-test.xml");
But i have exeption :The ' ' character, hexadecimal value 0x20, cannot be included in a name. Or so on.
How to make this element?
Thanks.
The method you're using for building XML is actually building a tree of objects (rather than as the textual representation of them), for for Schemas, you have to tell the document about them:
XmlDocument doc = new XmlDocument();
XmlSchemaSet xss = new XmlSchemaSet();
xss.Add("cim", "http://iec.ch/TC57/2009/CIM-schema-cim14#");
xss.Add("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
doc.Schemas = xss;
XmlNode rootNode = doc.CreateElement("rdf:RDF"); // This overload assumes the document already knows about the rdf schema as it is in the Schemas set
doc.AppendChild(rootNode);
If you can consider using Linq to XML, here's an alternative.
// Your data
var users = new List<User> {
new User { Name = "John", Age = 42 },
new User { Name = "Jane", Age = 39 }
};
// Project the data into XElements
var userElements =
from u in users
select
new XElement("user", u.Name,
new XAttribute("age", u.Age));
// Build the XML document, add namespaces and add the projected elements
var doc = new XDocument(
new XElement("RDF",
new XAttribute(XNamespace.Xmlns + "cim",
XNamespace.Get("http://iec.ch/TC57/2009/CIM-schema-cim14#")),
new XAttribute(XNamespace.Xmlns + "rdf",
XNamespace.Get("http://www.w3.org/1999/02/22-rdf-syntax-ns#")),
userElements
)
);
doc.Save(#"c:\xml-test.xml");
Related
I am trying to create a xml document of following format:
<![CDATA[<Caption xmlns="http:happy.x.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.happybus.tv/yy/happybus.xsd">
<TemplateID>xxxxx</TemplateID>
<CaptionOptions>
<CaptionField>
<Field>xxx</Field>
<Text>xxx</Text>
</CaptionField>
<CaptionField>
<Field>xxxx</Field>
<Text>""</Text>
</CaptionField>
</CaptionOptions>
</Caption>]]>
Here is the code that I wrote
XmlDocument xml2 = new XmlDocument();
XmlElement e = xml2.CreateElement("Caption");
e.InnerText ="Hello";
XmlElement template = xml2.CreateElement("TemplateID");
template.InnerText = "#TemplateID";
XmlElement captionOptions = xml2.CreateElement("CaptionOptions");
XmlElement captionField = xml2.CreateElement("CaptionField");
XmlElement fieldId = xml2.CreateElement("FieldID");
fieldId.InnerText = "#FieldID";
XmlElement textstring = xml2.CreateElement("TextString");
textstring.InnerText = "#TextString";
captionField.AppendChild(fieldId);
captionField.AppendChild(textstring);
captionOptions.AppendChild(captionField);
e.AppendChild(template);
e.AppendChild(captionOptions);
xml2.AppendChild(e);
StringWriter string_writer2 = new StringWriter();
XmlTextWriter xml_text_writer2 = new XmlTextWriter(string_writer2);
xml_text_writer2.Formatting = Formatting.Indented;
xml2.WriteTo(xml_text_writer2); // xml is your XmlDocument
string formattedXml2 = string_writer2.ToString();
Console.Write(formattedXml2);
I have tried a similar example with different XML doc but it clearly work, I even tried debugging but it is not getting formatted.
Have you tried using the XDocument and related classes? I find they make manual construction of xml easier and more intuitive since the code looks very similar to the xml. The ToString method seems to output the xml formatted the way you want:
void Main()
{
var xDoc = new XDocument
(
new XElement("Parent",
new XElement("TemplateID", "xxxxx"),
new XElement("CaptionOptions",
new XElement("CaptionField",
new XElement("Field", "xxx"),
new XElement("Text", "xxx")
),
new XElement("CaptionField",
new XElement("Field", "xxxx"),
new XElement("Text", "")
)
)
)
);
Console.WriteLine(xDoc.ToString());
//To enclose the xml in a CDATA, you could use:
var cData = new XCData(xDoc.ToString());
Console.WriteLine(cData.ToString());
}
I've spent so much time with this already, still can't get the value of NTE attribute. Can someone please help?
C#
StreamReader sr = new StreamReader(resp.GetResponseStream());
XPathDocument xmlDoc = new XPathDocument(sr); // holds xml document
XPathNavigator xmlNav = xmlDoc.CreateNavigator(); //evaluates XPath expressions
XPathNodeIterator node = xmlNav.Select("/DATA2SC/CALL");
string dne = xmlNav.GetAttribute("NTE", "");
Console.WriteLine(dne);
sr.Close();
XML
<?xml version="1.0"?>
<DATA2SC PIN="00000">
<CALL
TR_NUM="00000001"
STATUS="WAITING_FOR_APPROVAL"
NTE="$15.00">
<PROBLEM>
Text
</PROBLEM>
</CALL>
</DATA2SC>
Can you try this code please ?
I already check and it's work
StreamReader sr = new StreamReader("c:\\x.xml");
XPathDocument xmlDoc = new XPathDocument(sr); // holds xml document
XPathNavigator xmlNav = xmlDoc.CreateNavigator(); //evaluates XPath expressions
var node = xmlNav.SelectSingleNode("/DATA2SC/CALL");
string dne = node.GetAttribute("NTE", "");
Console.WriteLine(dne);
OR
XDocument docXmlWorld = XDocument.Load("c:\\x.xml");
foreach (var node1 in docXmlWorld.Descendants("DATA2SC"))
{
foreach (var node2 in node1.Descendants("CALL"))
{
string dne = node2.Attribute("NTE").Value;
Console.Out.WriteLine(dne);
}
}
Or you can do like this too:
XDocument docXmlWorld = XDocument.Load("c:\\x.xml");
//Get the first child => [DATA2SC]
XElement elementNodeDATA2SC = docXmlWorld.Element("DATA2SC");
//Get the first child => [CALL]
XElement elementNodeCALL = elementNodeDATA2SC.Element("CALL");
//Get the attribute NTE from [CALL] node
string dne = elementNodeCALL.Attribute("NTE").Value;
Console.Out.WriteLine(dne);
The Select method, returns a collection of all nodes with the specified XPath.
You can use SelectSingleNode, to select the first node.
var node = xmlNav.SelectSingleNode("/DATA2SC/CALL");
string dne = node.GetAttribute("NTE", "");
<CPT xmlns="http://www.example.org/genericClientProfile" xmlns:ns2="http://www.blahblah.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/genericClientProfile genericClientProfile.xsd">
<header>
<serviceId>CPT-UK</serviceId>
<versionId>1.0</versionId>
<brandCode>CUK</brandCode>
<creationTime>2013-09-26T13:55:32.31+02:00</creationTime>
</header>
</CPT>
I need to be able to read the elements in the header tag. I'm struggling to read the values for some reason, which i'm not sure of. What i've tried:
public ActionResult readxmldata()
{
using (var db = new CPTEntities())
{
var file = System.IO.Directory.GetFiles("C:\\Workspace\\CPTStaging","*.xml");
foreach (var xmldoc in file)
{
XmlDocument docpath = new XmlDocument();
docpath.Load(xmldoc);
CPTPROFILE doc = new CPTPROFILE();
db.SaveChanges();
H_HEADER header = new H_HEADER();
header.SERVICEID = docpath.SelectSingleNode("//CPT/header/#serviceId").Value;
header.VERSIONID = Convert.ToDecimal(docpath.SelectSingleNode("//CPT/header/#versionId").Value);
header.CREATIONTIME = Convert.ToDateTime(docpath.SelectSingleNode("//CPT/header/#creationTime").Value);
header.BRANDCODE = docpath.SelectSingleNode("//CPT/header/#brandCode").Value;
db.CPTPROFILEs.AddObject(doc);
db.SaveChanges();
}
}
Your XML uses namespaces. xmlns attribute declares default namespace. You should use it for each element of the XML.
XNamespace ns = "http://www.example.org/genericClientProfile";
XDocument doc = XDocument.Load(xmldoc);
XElement header = doc.Root.Element(ns + "header");
For comparison, here is one way to do it with Linq-to-XML:
XDocument doc = XDocument.Load(xmlFileName);
XNamespace ns = "http://www.example.org/genericClientProfile";
var header = doc.Descendants(ns+"header").Single();
H_HEADER header = new H_HEADER();
header.SERVICEID = (string) header.Element(ns + "serviceId");
header.VERSIONID = (double) header.Element(ns + "versionId");
header.BRANDCODE = (string) header.Element(ns + "brandCode");
header.CREATIONTIME = (DateTime) header.Element(ns + "creationTime");
I would like to add multiple records to the xml file and here is the code which i am using,
XmlTextWriter xwriter = new XmlTextWriter("C:\\Users\\Desktop\\TestFolder\\Xdoc1.xml", Encoding.UTF8);
xwriter.Formatting = Formatting.Indented;
xwriter.WriteStartElement("Employee");
xwriter.WriteStartElement("Person");
xwriter.WriteStartElement("Name");
xwriter.WriteString(textBox1.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Designation");
xwriter.WriteString(textBox2.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Employee ID");
xwriter.WriteString(textBox3.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Email");
xwriter.WriteString(textBox4.Text);
xwriter.WriteEndElement();
xwriter.WriteEndElement();
xwriter.WriteEndElement();
xwriter.Close();
the problem with this code is that only one record can be added. When i try to add the 2nd record, the previous record is overwritten.
Linq to XML makes xml task easier. Look at below code.
if (!System.IO.File.Exists("D:\\Employees.xml"))
{
XElement element = new XElement("Employees");
element.Save("D:\\Employees.xml");
}
XElement doc = XElement.Load("D:\\Employees.xml");
XElement employee = new XElement("Employees",
new XElement("Employee",
new XElement("Person",
new XElement("Name",
textBox1.Text),
new XElement("Designation",
textBox2.Text),
new XElement("EmployeeID",
textBox3.Text),
new XElement("Email",
textBox4.Text))));
doc.Add(employee);
doc.Save("D:\\Employees.xml");
here is no need to convert xmlWriter class.
string xmlFile = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Candidates.xml");
xmldoc = new XmlDocument();
xmldoc.Load(xmlFile);
root = xmldoc.DocumentElement;
try
{
XmlNode CandidateNode = xmldoc.CreateNode(XmlNodeType.Element, "Candidate", "");
XmlNode id = xmldoc.CreateNode(XmlNodeType.Element, "CandidateId", "");
id.InnerText = "1";
CandidateNode.AppendChild(id);
XmlNode subPositionId = xmldoc.CreateNode(XmlNodeType.Element, "SubPositionId", "");
subPositionId.InnerText = candidate.PositionId.ToString();
CandidateNode.AppendChild(subPositionId);
XmlNode firstName = xmldoc.CreateNode(XmlNodeType.Element, "FirstName", "");
firstName.InnerText = candidate.FirstName;
XmlNode lastName = xmldoc.CreateNode(XmlNodeType.Element, "LastName", "");
lastName.InnerText = candidate.LastName;
CandidateNode.AppendChild(firstName);
CandidateNode.AppendChild(lastName);
root.AppendChild(CandidateNode);
xmldoc.Save(xmlFile);
This will help you.
I am trying to dynamically create a XML for a webservice but when I test the service I get the following error
XML Parsing Error: no element found
Location: http://stuiis.cms.gre.ac.uk/dd615/aspweb/WatCoursework/Service.asmx/getMusicdetailsSql
Line Number 1, Column 39:
--------------------------------------^
// Make a new XML document in memory.
XmlDocument doc = new XmlDocument();
// Fill this document with a root element
// named <Inventory>.
XmlElement musicInformation = doc.CreateElement("musicInformation");
using (SqlDataReader oDr = myCommand.ExecuteReader())
{
while (oDr.Read())
{
// Now, make a sub element named <Car> with
// an ID attribute.
XmlElement musicdetails = doc.CreateElement("musicdetails");
musicdetails.SetAttribute("m_id", oDr["m_id"].ToString());
// Build the data within the <Car> element.
XmlElement p_id = doc.CreateElement("p_id");
p_id.InnerText = oDr["p_id"].ToString();
XmlElement artistname = doc.CreateElement("artistname");
artistname.InnerText = oDr["artistname"].ToString();
XmlElement recordname = doc.CreateElement("recordname");
recordname.InnerText = oDr["recordname"].ToString();
XmlElement recordtype = doc.CreateElement("recordtype");
recordtype.InnerText = oDr["recordtype"].ToString();
XmlElement format = doc.CreateElement("format");
format.InnerText = oDr["format"].ToString();
XmlElement price = doc.CreateElement("price");
price.InnerText = oDr["price"].ToString();
musicdetails.AppendChild(p_id);
musicdetails.AppendChild(artistname);
musicdetails.AppendChild(recordname);
musicdetails.AppendChild(recordtype);
musicdetails.AppendChild(format);
musicdetails.AppendChild(price);
musicInformation.AppendChild(musicdetails);
}
return doc;
}
I think you forgot to add the musicInformation to the document:
}
doc.AppendChild(musicInformation);
return doc;
}