// Test adding a document type to the document. public void TestXmlDocumentAddDocumentType() { XmlDocument doc = new XmlDocument(); // Add the document type. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); AssertNull("XmlDocumentType (1)", type.ParentNode); AssertEquals("XmlDocumentType (2)", doc, type.OwnerDocument); doc.AppendChild(type); AssertEquals("XmlDocumentType (3)", doc, type.ParentNode); AssertEquals("XmlDocumentType (4)", doc, type.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(type); Fail("adding XmlDocumentType node twice"); } catch (InvalidOperationException) { // Success } try { doc.PrependChild(type); Fail("prepending XmlDocumentType node twice"); } catch (InvalidOperationException) { // Success } // Adding an XmlDeclaration after should fail. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); try { doc.AppendChild(decl); Fail("appending XmlDeclaration after XmlDocumentType"); } catch (InvalidOperationException) { // Success } // But adding XmlDeclaration before should succeed. doc.PrependChild(decl); }
/// <summary> /// Inspect an XML document. /// </summary> /// <param name="doc">The XML document to inspect.</param> private void InspectDocument(XmlDocument doc) { // inspect the declaration if (XmlNodeType.XmlDeclaration == doc.FirstChild.NodeType) { XmlDeclaration declaration = (XmlDeclaration)doc.FirstChild; if (!String.Equals("utf-8", declaration.Encoding, StringComparison.OrdinalIgnoreCase)) { if (this.OnError(InspectorTestType.DeclarationEncodingWrong, declaration, "The XML declaration encoding is not properly set to 'utf-8'.")) { declaration.Encoding = "utf-8"; } } } else // missing declaration { if (this.OnError(InspectorTestType.DeclarationMissing, null, "This file is missing an XML declaration on the first line.")) { XmlNode xmlDecl = doc.PrependChild(doc.CreateXmlDeclaration("1.0", "utf-8", null)); doc.InsertAfter(doc.CreateWhitespace("\r\n"), xmlDecl); } } // start inspecting the nodes at the document element this.InspectNode(doc.DocumentElement, 0); }
public string ToXML(Animal objAnimal, string animal) { string result; XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", String.Empty); doc.PrependChild(dec); XmlElement baseElem = doc.CreateElement(animal); doc.AppendChild(baseElem); XmlElement elem = null; Type idType = objAnimal.GetType(); foreach (MethodInfo propInfo in idType.GetMethods()) { object val = propInfo.ReturnParameter.ParameterType; elem = doc.CreateElement(propInfo.Name); elem.InnerText = val.ToString(); baseElem.AppendChild(elem); } result = baseElem.PreviousSibling.OuterXml.ToString() + Environment.NewLine + baseElem.OuterXml.ToString(); return(result); }
/// <summary> /// return a KML document /// </summary> /// <returns></returns> private XmlDocument getKmlDocument() { // Create the document. XmlDocument doc = new XmlDocument(); // Insert the xml processing instruction and the root node XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null); doc.PrependChild(dec); XmlNode commentnode = doc.CreateComment("Sentience 3D Perception System KML interface"); doc.AppendChild(commentnode); XmlElement nodeKml = doc.CreateElement("kml"); nodeKml.SetAttribute("xmlns", "http://earth.google.com/kml/2.1"); doc.AppendChild(nodeKml); XmlElement elem = getXml(doc); nodeKml.AppendChild(elem); return(doc); }
/// <summary> /// Return a string containing the metadata XML based on the settings added to this instance. /// The resulting XML will be signed, if the AsymmetricAlgoritm property has been set. /// </summary> public string ToXml(Encoding enc) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(Serialization.SerializeToXmlString(_entity)); // Add the correct encoding to the head element. if (doc.FirstChild is XmlDeclaration) { ((XmlDeclaration)doc.FirstChild).Encoding = enc.WebName; } else { doc.PrependChild(doc.CreateXmlDeclaration("1.0", enc.WebName, null)); } if (Sign) { SignDocument(doc); } return(doc.OuterXml); }
private void saveDuplicationSummary(string cpdSummaryFile, Dictionary <string, float> duplications) { xmlDocument = new XmlDocument(); xmlDocument.PrependChild(xmlDocument.CreateXmlDeclaration("1.0", "utf-8", "yes")); XmlNode modulesNode = xmlDocument.CreateElement("Modules"); xmlDocument.AppendChild(modulesNode); foreach (KeyValuePair <string, float> duplicationPair in duplications) { XmlNode moduleNode = xmlDocument.CreateElement("Module"); XmlAttribute moduleNameAttribute = xmlDocument.CreateAttribute("name"); moduleNameAttribute.Value = duplicationPair.Key; moduleNode.Attributes.Append(moduleNameAttribute); XmlAttribute moduleDuplicationAttribute = xmlDocument.CreateAttribute("duplication"); moduleDuplicationAttribute.Value = duplicationPair.Value.ToString(); moduleNode.Attributes.Append(moduleDuplicationAttribute); modulesNode.AppendChild(moduleNode); } try { XmlTextWriter writer = new XmlTextWriter(cpdSummaryFile, null); writer.Formatting = Formatting.Indented; writer.Indentation = 2; xmlDocument.Save(writer); writer.Close(); } catch (Exception e) { System.Console.WriteLine("\ncpd-summary.xml File write error! File: {0}\n Exception: {1}" , cpdSummaryFile , e.StackTrace); } }
/// <summary> /// return an Xml document containing sensor model parameters /// </summary> /// <returns>xml document object</returns> private XmlDocument getXmlDocument(bool integer_version) { // Create the document. XmlDocument doc = new XmlDocument(); // Insert the xml processing instruction and the root node XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null); doc.PrependChild(dec); XmlNode commentnode = doc.CreateComment("Sentience 3D Perception System"); doc.AppendChild(commentnode); XmlElement nodeSentience = doc.CreateElement("Sentience"); doc.AppendChild(nodeSentience); if (integer_version) { nodeSentience.AppendChild(getXmlInteger(doc, nodeSentience)); } else { nodeSentience.AppendChild(getXml(doc, nodeSentience)); } return(doc); }
/// <summary> /// Return a string containing the metadata XML based on the settings added to this instance. /// The resulting XML will be signed, if the AsymmetricAlgorithm property has been set. /// </summary> /// <param name="encoding">The encoding.</param> /// <param name="certificate">Certificate to be used for signing (if appropriate)</param> /// <returns>The XML.</returns> public string ToXml(Encoding encoding, X509Certificate2 certificate) { encoding = encoding ?? Encoding.UTF8; var doc = new XmlDocument { PreserveWhitespace = true }; doc.LoadXml(Serialization.SerializeToXmlString(Entity)); // Add the correct encoding to the head element. if (doc.FirstChild is XmlDeclaration) { ((XmlDeclaration)doc.FirstChild).Encoding = encoding.WebName; } else { doc.PrependChild(doc.CreateXmlDeclaration("1.0", encoding.WebName, null)); } if (Sign) { SignDocument(doc, certificate); } return(doc.OuterXml); }
/// <summary> /// Adds an XML Declaration node to the document if it does not exist /// </summary> /// <param name="dom">the target document</param> public static void AddDeclaration(this XmlDocument dom) { if (dom.FirstChild.NodeType != XmlNodeType.XmlDeclaration) { dom.PrependChild(dom.CreateNode(XmlNodeType.XmlDeclaration, null, null)); } }
/// <summary> /// 写入 /// </summary> public void Write(IMemento memento, Stream stream) { //1. 写入根结点内容 XmlDocument xmlDocument = new XmlDocument(); XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "gb2312", "yes"); xmlDocument.PrependChild(xmlDeclaration); XmlElement rootNode = xmlDocument.CreateElement(memento.Name); xmlDocument.AppendChild(rootNode); //2. 写入根结点属性信息 for (int index = 0; index <= memento.GetAttributeCount() - 1; index++) { XmlAttribute attributeNode = xmlDocument.CreateAttribute(memento.GetAttributeName(index)); attributeNode.Value = memento.GetAttributeValue(index); rootNode.SetAttributeNode(attributeNode); } //3. 写入子结点内容 for (int index = 0; index <= memento.ChildCount - 1; index++) { IMemento childMemento = memento.GetChild(index); ProcessMemento(childMemento, rootNode, xmlDocument); } xmlDocument.Save(stream); }
/// <summary> /// return an Xml document containing the status of the given list of devices /// </summary> /// <returns></returns> protected static XmlDocument GetDeviceStatus( ArrayList devs, string status_type) { XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", XML_ENCODING, null); doc.PrependChild(dec); XmlElement statusreply = doc.CreateElement(status_type); doc.AppendChild(statusreply); for (int i = 0; i < devs.Count; i += 2) { string Id = (string)devs[i]; List <string> required_properties = (List <string>)devs[i + 1]; XmlElement status = GetDeviceStatus(Id, doc, statusreply, required_properties); if (status != null) { statusreply.AppendChild(status); } } //doc.Save("DeviceStatus.xml"); return(doc); }
/// <summary> /// Convert to xml string /// </summary> /// <param name="doc"></param> /// <param name="xmlHeader"></param> /// <param name="format"></param> /// <returns></returns> public static string ToXmlString(this XmlDocument doc, bool xmlHeader = true, bool format = true) { Expect.IsNotNull(doc, nameof(doc)); var sb = new StringBuilder(); var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false), ConformanceLevel = ConformanceLevel.Document, }; if (xmlHeader) { var instruction = doc.CreateProcessingInstruction("xml", "version='1.0' encoding='utf-8'"); doc.PrependChild(instruction); } else { settings.OmitXmlDeclaration = true; } if (format) { settings.Indent = true; settings.IndentChars = " "; } using (var writer = XmlWriter.Create(sb, settings)) { doc.WriteTo(writer); } return(sb.ToString()); }
/// <summary> /// Return a string containing the metadata XML based on the settings added to this instance. /// The resulting XML will be signed, if the AsymmetricAlgorithm property has been set. /// </summary> /// <param name="encoding">The encoding.</param> /// <param name="sign">if the document should be signed</param> /// <param name="certificate">Certificate to be used for signing (if appropriate)</param> /// <returns>The XML.</returns> public string ToXml(Encoding encoding, X509Certificate2 certificate, AlgorithmType signatureAlgorithm) { if (Entity == null) { throw new InvalidOperationException("You are trying to sign an empty or uninitialized metadata document"); } encoding = encoding ?? Encoding.UTF8; var doc = new XmlDocument { PreserveWhitespace = true }; doc.LoadXml(Serialization.SerializeToXmlString(Entity)); // Add the correct encoding to the head element. if (doc.FirstChild is XmlDeclaration) { ((XmlDeclaration)doc.FirstChild).Encoding = encoding.WebName; } else { doc.PrependChild(doc.CreateXmlDeclaration("1.0", encoding.WebName, null)); } if (certificate != null) { SignDocument(doc, certificate, signatureAlgorithm); } return(doc.OuterXml); }
/// <summary> /// Return a string containing the metadata XML based on the settings added to this instance. /// The resulting XML will be signed, if the AsymmetricAlgoritm property has been set. /// </summary> public string ToXml(Encoding enc) { XmlDocument doc = new XmlDocument(); doc.XmlResolver = null; doc.PreserveWhitespace = true; doc.LoadXml(Serialization.SerializeToXmlString(_entity)); // Add the correct encoding to the head element. if (doc.FirstChild is XmlDeclaration) { ((XmlDeclaration)doc.FirstChild).Encoding = enc.WebName; } else { doc.PrependChild(doc.CreateXmlDeclaration("1.0", enc.WebName, null)); } if (Sign) { var metaDataShaHashingAlgorithm = FederationConfig.GetConfig().MetaDataShaHashingAlgorithm; var validatedMetaDataShaHashingAlgorithm = SignatureProviderFactory.ValidateShaHashingAlgorithm(metaDataShaHashingAlgorithm); var signatureProvider = SignatureProviderFactory.CreateFromShaHashingAlgorithmName(validatedMetaDataShaHashingAlgorithm); var cert = FederationConfig.GetConfig().SigningCertificate.GetCertificate(); signatureProvider.SignMetaData(doc, doc.DocumentElement.GetAttribute("ID"), cert); } return(doc.OuterXml); }
/// <summary> /// return an Xml document containing camera calibration parameters /// </summary> /// <returns></returns> private XmlDocument getXmlDocument() { // Create the document. XmlDocument doc = new XmlDocument(); // Insert the xml processing instruction and the root node XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null); doc.PrependChild(dec); XmlNode commentnode = doc.CreateComment("Sentience 3D Perception System"); doc.AppendChild(commentnode); XmlElement nodeCalibration = doc.CreateElement("Sentience"); doc.AppendChild(nodeCalibration); xml.AddComment(doc, nodeCalibration, "Calibration apparatus setup parameters"); XmlElement nodeCalibSetup = doc.CreateElement("CalibrationSetup"); nodeCalibration.AppendChild(nodeCalibSetup); xml.AddComment(doc, nodeCalibSetup, "Horizontal field of view of the camera in degrees"); xml.AddTextElement(doc, nodeCalibSetup, "FieldOfViewDegrees", txtFOV.Text); xml.AddComment(doc, nodeCalibSetup, "Position of the centre spot relative to the centre of the calibration pattern"); xml.AddComment(doc, nodeCalibSetup, "0 - North West"); xml.AddComment(doc, nodeCalibSetup, "1 - North East"); xml.AddComment(doc, nodeCalibSetup, "2 - South East"); xml.AddComment(doc, nodeCalibSetup, "3 - South West"); xml.AddTextElement(doc, nodeCalibSetup, "CentreSpotPosition", Convert.ToString(cmbCentreSpotPosition.SelectedIndex)); xml.AddComment(doc, nodeCalibSetup, "Distance from the camera to the centre of the calibration pattern along the ground in mm"); xml.AddTextElement(doc, nodeCalibSetup, "DistToCentreMillimetres", txtDistToCentre.Text); xml.AddComment(doc, nodeCalibSetup, "height of the camera above the ground in mm"); xml.AddTextElement(doc, nodeCalibSetup, "CameraHeightMillimetres", txtCameraHeight.Text); xml.AddComment(doc, nodeCalibSetup, "Calibration pattern spacing in mm"); xml.AddTextElement(doc, nodeCalibSetup, "PatternSpacingMillimetres", txtPatternSpacing.Text); xml.AddComment(doc, nodeCalibSetup, "Baseline Distance mm"); xml.AddTextElement(doc, nodeCalibSetup, "BaselineMillimetres", txtBaseline.Text); if (cam.leftcam.ROI != null) { xml.AddComment(doc, nodeCalibSetup, "Region of interest in the left image"); xml.AddTextElement(doc, nodeCalibSetup, "LeftROI", Convert.ToString(cam.leftcam.ROI.tx) + "," + Convert.ToString(cam.leftcam.ROI.ty) + "," + Convert.ToString(cam.leftcam.ROI.bx) + "," + Convert.ToString(cam.leftcam.ROI.by)); } if (cam.rightcam.ROI != null) { xml.AddComment(doc, nodeCalibSetup, "Region of interest in the right image"); xml.AddTextElement(doc, nodeCalibSetup, "RightROI", Convert.ToString(cam.rightcam.ROI.tx) + "," + Convert.ToString(cam.rightcam.ROI.ty) + "," + Convert.ToString(cam.rightcam.ROI.bx) + "," + Convert.ToString(cam.rightcam.ROI.by)); } return(doc); }
public void writeResultsToXmlFile() { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.PrependChild(xmlDocument.CreateXmlDeclaration("1.0", "utf-8", "yes")); XmlNode testSuiteNode = xmlDocument.CreateElement("testsuite"); XmlAttribute testSuiteAttribute = xmlDocument.CreateAttribute("name"); testSuiteAttribute.Value = "Thresholder tests"; testSuiteNode.Attributes.Append(testSuiteAttribute); xmlDocument.AppendChild(testSuiteNode); foreach (ComparatorResult comparatorResult in comparatorResults) { XmlNode testCaseNode = xmlDocument.CreateElement("testcase"); XmlAttribute testCaseNameAttribute = xmlDocument.CreateAttribute("name"); testCaseNameAttribute.Value = comparatorResult.getName(); testCaseNode.Attributes.Append(testCaseNameAttribute); XmlAttribute testCaseTimeAttribute = xmlDocument.CreateAttribute("time"); testCaseTimeAttribute.Value = (comparatorResult.getDuration() / 1000.0).ToString(); testCaseNode.Attributes.Append(testCaseTimeAttribute); testSuiteNode.AppendChild(testCaseNode); if (!comparatorResult.isPass()) { XmlNode failureNode = xmlDocument.CreateElement("failure"); String text; if (float.IsNaN(comparatorResult.getActualValue())) { text = String.Format("There is no data for {0}", comparatorResult.getName()); } else { text = String.Format("Degradation is {0:0.##}% , current result is {1}, threshold is {2}" , comparatorResult.getDifference() * 100 , comparatorResult.getActualValue().ToString() , comparatorResult.getOriginalValue().ToString()); } failureNode.AppendChild(xmlDocument.CreateTextNode(text)); testCaseNode.AppendChild(failureNode); } } try { XmlTextWriter writer = new XmlTextWriter(outputFile, null); writer.Formatting = Formatting.Indented; writer.Indentation = 2; xmlDocument.Save(writer); writer.Close(); System.Console.WriteLine("\nJUnit report xml is written. File: {0}", outputFile); } catch (Exception e) { System.Console.WriteLine("\nComparator results xml File write error! File: {0}\n Exception: {1}" , outputFile , e.StackTrace); } }
/// <summary> /// This private method generates a list of files in a directory as XML and /// returns the XML as a W3C DOM document using the DOM calls. /// </summary> /// <param name="strDirectory">List files in this directory</param> /// <returns>A W3C DOM docuemnt with the directory file list</returns> public static XmlDocument GetXmlUsingDomCalls(string strDirectory) { // Create the document. XmlDocument doc = new XmlDocument(); // Insert the xml processing instruction and the root node XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "", "yes"); doc.PrependChild(dec); // Add the root element XmlElement nodeElem = doc.CreateElement("dirlist"); doc.AppendChild(nodeElem); Boolean bFirst = true; // Process the directory list DirectoryInfo dir = new DirectoryInfo(strDirectory); foreach (FileSystemInfo entry in dir.GetFileSystemInfos()) { if (bFirst == true) { // If we haven't added any elements yet, go ahead and add a text element which // contains the full directory path. XmlElement root = doc.DocumentElement; String strFullName = entry.FullName; String strFileName = entry.Name; String strDir = strFullName.Substring(0, strFullName.Length - strFileName.Length); root.SetAttribute("dir", strDir); bFirst = false; } // Add a new text node with a tag entry. There will be one added per // item encountered in the directory. XmlElement elem = doc.CreateElement("entry"); doc.DocumentElement.AppendChild(elem); // Write out the things we are interested in about this entry in the // directory. addTextElement(doc, elem, "name", entry.Name); addTextElement(doc, elem, "created", entry.CreationTime.ToString()); addTextElement(doc, elem, "lastaccess", entry.LastAccessTime.ToString()); addTextElement(doc, elem, "lastwrite", entry.LastWriteTime.ToString()); addTextElement(doc, elem, "isfile", ((entry.Attributes & FileAttributes.Directory) > 0) ? "False" : "True"); addTextElement(doc, elem, "isdir", ((entry.Attributes & FileAttributes.Directory) > 0) ? "True" : "False"); addTextElement(doc, elem, "readonly", ((entry.Attributes & FileAttributes.ReadOnly) > 0) ? "True" : "False"); } return(doc); }
private static void initDoc() { doc = new XmlDocument(); XmlDeclaration xmlDec = doc.CreateXmlDeclaration("1.0", "", "yes"); doc.PrependChild(xmlDec); root = doc.CreateElement(KEY_MODEL); doc.AppendChild(root); }
public PerformanceSummary(String focusProduct) { // example "CreateXMLDoc" from http://www.fincher.org/tips/Languages/csharp.shtml _model = new XmlDocument(); _model.PrependChild(_model.CreateXmlDeclaration("1.0", "utf-8", "yes")); _root = _model.CreateElement(_tagBenchmark); _model.AppendChild(_root); _focusProduct = focusProduct; }
/// <summary> /// Creates an instance of an XML document that contains the XML processing instruction and is initialized with the data loaded from the specified stream. /// </summary> /// <param name="data">The data stream supplying data for the new XML document.</param> /// <returns>An instance of the <see cref="System.Xml.XmlDocument"/> class.</returns> public static XmlDocument CreateXmlDocument(Stream data) { XmlDocument document = new XmlDocument(); document.PreserveWhitespace = false; document.Load(data); document.PrependChild(document.CreateXmlDeclaration("1.0", Encoding.Unicode.WebName, String.Empty)); return(document); }
public static bool SavePlistToFile(String xmlFile, Hashtable plist) { // If the hashtable is null, then there's apparently an issue; fail out. if (plist == null) { Debug.LogError("Passed a null plist hashtable to SavePlistToFile."); return(false); } // Create the base xml document that we will use to write the data XmlDocument xml = new XmlDocument(); xml.XmlResolver = null; //Disable schema/DTD validation, it's not implemented for Unity. // Create the root XML declaration // This, and the DOCTYPE, below, are standard parts of a XML property list file XmlDeclaration xmldecl = xml.CreateXmlDeclaration("1.0", "UTF-8", null); xml.PrependChild(xmldecl); // Create the DOCTYPE XmlDocumentType doctype = xml.CreateDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null); xml.AppendChild(doctype); // Create the root plist node, with a version number attribute. // Every plist file has this as the root element. We're using version 1.0 of the plist scheme XmlNode plistNode = xml.CreateNode(XmlNodeType.Element, "plist", null); XmlAttribute plistVers = (XmlAttribute)xml.CreateNode(XmlNodeType.Attribute, "version", null); plistVers.Value = "1.0"; plistNode.Attributes.Append(plistVers); xml.AppendChild(plistNode); // Now that we've created the base for the XML file, we can add all of our information to it. // Pass the plist data and the root dict node to SaveDictToPlistNode, which will write the plist data to the dict node. // This function will itterate through the hashtable hierarchy and call itself recursively for child hashtables. if (!SaveDictToPlistNode(plistNode, plist)) { // If for some reason we failed, post an error and return false. Debug.LogError("Failed to save plist data to root dict node: " + plist); return(false); } else // We were successful // Create a StreamWriter and write the XML file to disk. // (do not append and UTF-8 are default, but we're defining it explicitly just in case) { StreamWriter sw = new StreamWriter(xmlFile, false, System.Text.Encoding.UTF8); xml.Save(sw); sw.Close(); } // We're done here. If there were any failures, they would have returned false. // Return true to indicate success. return(true); }
public static XmlDocument ToXmlDocument(this object obj) { XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", String.Empty); xmlDoc.PrependChild(xmlDec); var node = Process(xmlDoc, obj, obj.GetType(), null); xmlDoc.AppendChild(node); return(xmlDoc); }
protected virtual XmlDocument GetUpdateCommand([NotNull] EntityProperties property) { Assert.ArgumentNotNull(property, "property"); var doc = new XmlDocument(); XmlElement elementBatch = doc.CreateElement("Batch"); elementBatch.SetAttribute("OnError", "Continue"); elementBatch.SetAttribute("ListVersion", "0"); elementBatch.SetAttribute("PreCalc", "TRUE"); XmlElement elementMethod = doc.CreateElement("Method"); elementMethod.SetAttribute("ID", "1"); elementMethod.SetAttribute("Cmd", property["ows_ID"].IsNew ? "New" : "Update"); elementBatch.PrependChild(elementMethod); XmlElement elementField = doc.CreateElement("Field"); elementField.SetAttribute("Name", "ID"); elementField.InnerXml = property["ows_ID"].Value; elementMethod.PrependChild(elementField); bool needUpdate = false; foreach (var key in property.Keys) { // TODO: [101209 dan] Research what is the difference between "empty" and "null" values of SharePoint fields. // TODO: [101209 dan] Research in correct way to update SharePopint fields. // We can't rely on "this.PropertiesCopy" property to find previously existed SharePoint properties, // because "this.PropertiesCopy" does not contain all properties. if (property[key].IsChanged || property[key].IsNew) { elementField = doc.CreateElement("Field"); elementField.SetAttribute("Name", key.Replace("ows_", string.Empty)); elementField.InnerXml = HttpUtility.HtmlEncode(property[key].Value); elementMethod.PrependChild(elementField); needUpdate = true; } } doc.PrependChild(elementBatch); if (needUpdate) { return(doc); } return(null); }
private void createEmptyXMLDocument() { // Create a new DOM-based XML document m_xmlDocument = new XmlDocument(); // Add the XML declaration XmlDeclaration dec = m_xmlDocument.CreateXmlDeclaration("1.0", "utf-8", "yes"); m_xmlDocument.PrependChild(dec); // Add the root element XmlElement nodeElem = m_xmlDocument.CreateElement("FeatureDB"); m_xmlDocument.AppendChild(nodeElem); }
public static XmlDocument XslExportTransform(XmlDocument doc) { XmlReader reader = Registry.GladeExportXsl.Transform(doc, null, (XmlResolver)null); doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(reader); XmlDocumentType doctype = doc.CreateDocumentType("glade-interface", null, Glade20SystemId, null); doc.PrependChild(doctype); return(doc); }
private string ParseOptionsControls() { XmlDocument xDoc = new XmlDocument(); XmlElement options = xDoc.CreateElement("options"); xDoc.AppendChild(options); XmlElement settings = xDoc.CreateElement("settings"); options.AppendChild(settings); foreach (TreeNode tn in topLevel.Nodes) { if (tn.Tag != null && typeof(TableLayoutPanel).IsInstanceOfType(tn.Tag)) { XmlElement panel = xDoc.CreateElement("panel"); panel.SetAttribute("name", tn.Text); settings.AppendChild(panel); XmlElement controls = xDoc.CreateElement("controls"); panel.AppendChild(controls); foreach (Control c in ((TableLayoutPanel)tn.Tag).Controls) { if (!typeof(Label).IsInstanceOfType(c)) { int firstPos = c.ToString().IndexOf(','); int lastPos = c.ToString().Substring(0, firstPos).LastIndexOf('.'); string ctrlType = c.ToString().Substring(0, firstPos).Substring(lastPos + 1).Trim(); string ctrlValue = string.Empty; if (ctrlType.ToLower().Equals("textbox")) { ctrlValue = "Text: " + c.Text; } else { ctrlValue = c.ToString().Substring(firstPos + 1).Trim(); } XmlElement ctrl = xDoc.CreateElement("control"); ctrl.SetAttribute("name", c.Name); ctrl.SetAttribute("type", ctrlType); ctrl.InnerText = ctrlValue; controls.AppendChild(ctrl); } } } } XmlDeclaration declare = xDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); xDoc.PrependChild(declare); _values = xDoc.OuterXml; return(_values); }
//run an XSLT transform. //transformFile is the name of the .xsl to run; //path is usually tools directory (be sure to include final slash in passed string) //takes two paramaters and corresponding values; use empty strings if not needed static public XmlDocument performTransformWith2Params(XmlDocument inDOM, string path, string transformFile, string param1Name, string param1Value, string param2Name, string param2Value) { // Create a Processor instance. Processor processor = new Processor(); // Load the source document, building a tree XmlNode node = inDOM; XdmNode input = processor.NewDocumentBuilder().Build(node); // Compile the stylesheet XsltExecutable exec = processor.NewXsltCompiler().Compile(new XmlTextReader(path.Replace("Program Files", "PROGRA~1") + transformFile)); // Create a transformer XsltTransformer transformer = exec.Load(); string xdmToolsPath = "file:/" + path.Replace("\\", "/").Replace(" ", "%20"); // Run it once // Set parameters transformer.SetParameter(new QName("", "", "include-attributes"), new XdmAtomicValue(false)); //following may be needed if xslt itself needs to find other files transformer.SetParameter(new QName("", "", "localBaseUri"), new XdmAtomicValue(xdmToolsPath.Replace("Program%20Files", "PROGRA~1"))); //optionally add another parameter if (!String.IsNullOrEmpty(param1Name)) { transformer.SetParameter(new QName("", "", param1Name), new XdmAtomicValue(param1Value)); } //and another param if (!String.IsNullOrEmpty(param2Name)) { transformer.SetParameter(new QName("", "", param2Name), new XdmAtomicValue(param2Value)); } transformer.InitialContextNode = input; XdmDestination results = new XdmDestination(); transformer.Run(results); XmlDocument resultXmlDoc = new XmlDocument(); resultXmlDoc.LoadXml(results.XdmNode.OuterXml); XmlDeclaration declaration = resultXmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); resultXmlDoc.PrependChild(declaration); // return the result return(resultXmlDoc); }
/// <summary> /// return an Xml document used as a reply to the client after an update of parameters has been received and carried out /// </summary> /// <returns>reply xml document</returns> protected static XmlDocument GetDeviceUpdateReply() { XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", XML_ENCODING, null); doc.PrependChild(dec); XmlElement statusreply = doc.CreateElement(STATUS_REPLY); doc.AppendChild(statusreply); //doc.Save("DeviceUpdateReply.xml"); return(doc); }
public void PreviewXmlFile(int projectId) { var project = _repository.Get(projectId); var json = JsonConvert.SerializeObject(project); XmlDocument xml = JsonConvert.DeserializeXmlNode(json, "ProjectViewModel"); xml.PrependChild(xml.CreateProcessingInstruction( "xml-stylesheet", "type='text/xsl' href='template.xslt'")); Response.Clear(); Response.Write(xml.OuterXml); Response.ContentType = "text/xml"; Response.End(); }
public FileResult ExportXmlFile(int projectId) { var project = _repository.Get(projectId); project.Images = null; var json = JsonConvert.SerializeObject(project); XmlDocument xml = JsonConvert.DeserializeXmlNode(json, "ProjectViewModel"); xml.PrependChild(xml.CreateProcessingInstruction( "xml-stylesheet", "type='text/xsl' href='template.xslt'")); return(File(Encoding.UTF8.GetBytes(xml.OuterXml), "application/xml", project.Title + ".xml")); }
public static bool SavePlistToFile(String xmlFile, Hashtable plist) { // If the hashtable is null, then there's apparently an issue; fail out. if (plist == null) { Debug.LogError("Passed a null plist hashtable to SavePlistToFile."); return false; } // Create the base xml document that we will use to write the data XmlDocument xml = new XmlDocument(); xml.XmlResolver = null; //Disable schema/DTD validation, it's not implemented for Unity. // Create the root XML declaration // This, and the DOCTYPE, below, are standard parts of a XML property list file XmlDeclaration xmldecl = xml.CreateXmlDeclaration("1.0", "UTF-8", null); xml.PrependChild(xmldecl); // Create the DOCTYPE XmlDocumentType doctype = xml.CreateDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null); xml.AppendChild(doctype); // Create the root plist node, with a version number attribute. // Every plist file has this as the root element. We're using version 1.0 of the plist scheme XmlNode plistNode = xml.CreateNode(XmlNodeType.Element, "plist", null); XmlAttribute plistVers = (XmlAttribute)xml.CreateNode(XmlNodeType.Attribute, "version", null); plistVers.Value = "1.0"; plistNode.Attributes.Append(plistVers); xml.AppendChild(plistNode); // Now that we've created the base for the XML file, we can add all of our information to it. // Pass the plist data and the root dict node to SaveDictToPlistNode, which will write the plist data to the dict node. // This function will itterate through the hashtable hierarchy and call itself recursively for child hashtables. if (!SaveDictToPlistNode(plistNode, plist)) { // If for some reason we failed, post an error and return false. Debug.LogError("Failed to save plist data to root dict node: " + plist); return false; } else { // We were successful // Create a StreamWriter and write the XML file to disk. // (do not append and UTF-8 are default, but we're defining it explicitly just in case) StreamWriter sw = new StreamWriter(xmlFile, false, System.Text.Encoding.UTF8); xml.Save(sw); sw.Close(); } // We're done here. If there were any failures, they would have returned false. // Return true to indicate success. return true; }
// Test adding an XML declaration to the document. public void TestXmlDocumentAddXmlDeclaration() { XmlDocument doc = new XmlDocument(); // Add the declaration. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); AssertNull("XmlDeclaration (1)", decl.ParentNode); AssertEquals("XmlDeclaration (2)", doc, decl.OwnerDocument); doc.AppendChild(decl); AssertEquals("XmlDeclaration (3)", doc, decl.ParentNode); AssertEquals("XmlDeclaration (4)", doc, decl.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(decl); Fail("adding XmlDeclaration node twice"); } catch(InvalidOperationException) { // Success } try { doc.PrependChild(decl); Fail("prepending XmlDeclaration node twice"); } catch(InvalidOperationException) { // Success } // Adding a document type before should fail. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); try { doc.PrependChild(type); Fail("prepending XmlDocumentType"); } catch(InvalidOperationException) { // Success } // Adding a document type after should succeed. doc.AppendChild(type); // Adding an element before should fail. XmlElement element = doc.CreateElement("foo"); try { doc.PrependChild(element); Fail("prepending XmlElement"); } catch(InvalidOperationException) { // Success } // Adding the element between decl and type should fail. try { doc.InsertAfter(element, decl); Fail("inserting XmlElement between XmlDeclaration " + "and XmlDocumentType"); } catch(InvalidOperationException) { // Success } try { doc.InsertBefore(element, type); Fail("inserting XmlElement between XmlDeclaration " + "and XmlDocumentType (2)"); } catch(InvalidOperationException) { // Success } // Adding an element after should succeed. doc.AppendChild(element); }
// Test adding an element to the document. public void TestXmlDocumentAddElement() { XmlDocument doc = new XmlDocument(); // Add an element to the document. XmlElement element = doc.CreateElement("foo"); AssertNull("XmlElement (1)", element.ParentNode); AssertEquals("XmlElement (2)", doc, element.OwnerDocument); doc.AppendChild(element); AssertEquals("XmlElement (3)", doc, element.ParentNode); AssertEquals("XmlElement (4)", doc, element.OwnerDocument); // Try to add it again, which should fail this time. try { doc.AppendChild(element); Fail("adding XmlElement node twice"); } catch(InvalidOperationException) { // Success } try { doc.PrependChild(element); Fail("prepending XmlElement node twice"); } catch(InvalidOperationException) { // Success } // Adding an XmlDeclaration after should fail. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", null, null); try { doc.AppendChild(decl); Fail("appending XmlDeclaration after XmlElement"); } catch(InvalidOperationException) { // Success } // But adding XmlDeclaration before should succeed. doc.PrependChild(decl); // Adding a document type after should fail. XmlDocumentType type = doc.CreateDocumentType("foo", null, null, null); try { doc.AppendChild(type); Fail("appending XmlDocumentType"); } catch(InvalidOperationException) { // Success } // Adding a document type before should succeed. doc.InsertBefore(type, element); }