/// <summary> /// Exports the tree. /// </summary> /// <param name="root">The root element.</param> /// <param name="includeRoot">if set to <c>true</c> the also export the root element, else /// if set to <c>false</c>, then the children are exported.</param> public void ExportTree(EATree root, bool includeRoot) { m_XmlDocument = new XmlDocument() { XmlResolver = null }; XmlDocumentFragment xmlFragment = m_XmlDocument.CreateDocumentFragment(); DocBookFormat format = new DocBookFormat(); if (includeRoot) { XmlNode xnode = ExportElement(root, format); xmlFragment.AppendChild(xnode); } else { foreach (EATree child in root.Children) { XmlNode xnode = ExportElement(child, format); xmlFragment.AppendChild(xnode); } } xmlFragment.WriteContentTo(m_XmlWriter); }
public void GetInnerXml() { // this will be also tests of TestWriteTo()/TestWriteContentTo() document = new XmlDocument(); fragment = document.CreateDocumentFragment(); fragment.AppendChild(document.CreateElement("foo")); fragment.AppendChild(document.CreateElement("bar")); fragment.AppendChild(document.CreateElement("baz")); Assert.AreEqual("<foo /><bar /><baz />", fragment.InnerXml, "#Simple"); }
public TransparentXmlFragment(bool init) { elem1 = "3"; elem3 = "4"; XmlDocument doc = new XmlDocument(); _frag = doc.CreateDocumentFragment(); XmlNode node = _frag.AppendChild(doc.CreateElement("sub1")); node.AppendChild(doc.CreateElement("extra")); _frag.AppendChild(doc.CreateElement("sub2")).InnerText = "2"; }
protected void MoveChildNodes(XmlDocumentFragment fragment, XmlElement element) { while (element.ChildNodes.Count > 0) { fragment.AppendChild(element.ChildNodes[0]); } }
private static XmlDocumentFragment LoadDocumentFragment(Stream stream) { XmlDocument xmlDoc = new XmlDocument() { XmlResolver = null }; XmlDocumentFragment fragment = xmlDoc.CreateDocumentFragment(); XmlReaderSettings xrs = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment, DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; using (XmlReader xr = XmlReader.Create(stream, xrs)) { XmlNode node; do { node = xmlDoc.ReadNode(xr); if (node != null) { fragment.AppendChild(node); } } while (node != null); } return(fragment); }
public void AppendFragmentToElement() { document = new XmlDocument(); fragment = document.CreateDocumentFragment(); document.LoadXml("<html><head></head><body></body></html>"); XmlElement body = document.DocumentElement.LastChild as XmlElement; fragment.AppendChild(document.CreateElement("p")); fragment.AppendChild(document.CreateElement("div")); // appending fragment to element body.AppendChild(fragment); Assert.IsNotNull(body.FirstChild, "#AppendFragmentToElement.Exist"); Assert.AreEqual(XmlNodeType.Element, body.FirstChild.NodeType, "#AppendFragmentToElement.ChildIsElement"); Assert.AreEqual("p", body.FirstChild.Name, "#AppendFragmentToElement.FirstChild"); Assert.AreEqual("div", body.LastChild.Name, "#AppendFragmentToElement.LastChild"); }
/// <summary> /// Return the document fragment. /// </summary> /// <returns>The document fragment</returns> internal XmlDocumentFragment getDocumentFragment() { XmlDocumentFragment rv = document.CreateDocumentFragment(); XmlNode rootElt = document.FirstChild; while (rootElt.HasChildNodes) { rv.AppendChild(rootElt.FirstChild); } document = null; return(rv); }
public static XmlNode CreateTemporaryDomNode() { string tmpName = "tmp"; if (tmpFragment == null) { tmpFragment = GetTemporaryDocument().CreateDocumentFragment(); tmpDocument.AppendChild(tmpFragment); } XmlNode node = GetTemporaryDocument().CreateElement(tmpName); tmpFragment.AppendChild(node); return(node); }
private static XmlDocumentFragment CreateFragmentWithTargetNodes(string query, XmlDocument document) { //find the nodes specified in the XML query XmlNodeList list = document.SelectNodes(query); XmlDocumentFragment fragment = document.CreateDocumentFragment(); foreach (XmlNode node in list) { // We must clone the node, otherwise, AppendChild merely MOVES it, // modifying the document we have cached, and causing a repeat query for // the same element (or any of its children) to fail. fragment.AppendChild(node.Clone()); } return(fragment); }
public void AppendChildToFragment() { document = new XmlDocument(); fragment = document.CreateDocumentFragment(); document.LoadXml("<html><head></head><body></body></html>"); XmlElement el = document.CreateElement("p"); el.InnerXml = "Test Paragraph"; // appending element to fragment fragment.AppendChild(el); Assert.IsNotNull(fragment.FirstChild, "#AppendChildToFragment.Element"); Assert.IsNotNull(fragment.FirstChild.FirstChild, "#AppendChildToFragment.Element.Children"); Assert.AreEqual("Test Paragraph", fragment.FirstChild.FirstChild.Value, "#AppendChildToFragment.Element.Child.Text"); }
public static XmlNode Execute(XmlDocument dom, SqlCommand cmd) { //Retrieve the result into an XML XmlReader xr = cmd.ExecuteXmlReader(); XmlDocumentFragment xdf = dom.CreateDocumentFragment(); XmlNode xn; while ((xn = dom.ReadNode(xr)) != null) { xdf.AppendChild(xn); } xr.Close(); return(xdf); }
private static XmlNode NameValColWorkhorse(XmlNode parent, string name, string[] arVal, string nsName) { if (arVal == null) { return(null); } XmlDocumentFragment frag = parent.OwnerDocument.CreateDocumentFragment(); for (int x = 0; x < arVal.Length; x++) { XmlElement e = parent.OwnerDocument.CreateElement(name, nsName); e.InnerText = arVal[x]; frag.AppendChild(e); } return(frag); }
public override void Process(IXmlProcessorNodeList nodeList, IXmlProcessorEngine engine) { XmlProcessingInstruction node = nodeList.Current as XmlProcessingInstruction; XmlDocumentFragment fragment = CreateFragment(node); string expression = node.Data; // We don't have an expression evaluator right now, so expression will // be just pre-defined literals that we know how to evaluate object evaluated = ""; if (string.Compare(expression, "$basedirectory", true) == 0) { evaluated = AppDomain.CurrentDomain.BaseDirectory; } fragment.AppendChild(node.OwnerDocument.CreateTextNode(evaluated.ToString())); ReplaceNode(node.ParentNode, fragment, node); }
/// <summary> /// XmlNodeList의 Node들을 parentNode에 추가한다. /// </summary> /// <param name="parentNode">대상 Element</param> /// <param name="elementList">XmlNodeList 형식의 Element (같은 Level의 Element만 써야한다.)</param> /// <returns>추가된 XmlNode의 갯수</returns> public static int AddElementList(this XmlNode parentNode, XmlNodeList elementList) { var count = 0; if (elementList == null || elementList.Count == 0) { return(count); } CheckNull(parentNode); XmlDocumentFragment fragment = parentNode.OwnerDocument.CreateDocumentFragment(); foreach (XmlNode srcNode in elementList) { fragment.AppendChild(srcNode.CloneNode(true)); count++; } parentNode.AppendChild(fragment); return(count); }
public static void Main() { // Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml("<items/>"); // Create a document fragment. XmlDocumentFragment docFrag = doc.CreateDocumentFragment(); // Display the owner document of the document fragment. Console.WriteLine(docFrag.OwnerDocument.OuterXml); // Add nodes to the document fragment. Notice that the // new element is created using the owner document of // the document fragment. XmlElement elem = doc.CreateElement("item"); elem.InnerText = "widget"; docFrag.AppendChild(elem); Console.WriteLine("Display the document fragment..."); Console.WriteLine(docFrag.OuterXml); }
/// <summary> /// Returns SubResults node outerxml. /// </summary> /// <returns></returns> public string GetSubResultXml(bool comparenode) { XmlDocument xmldoc = new XmlDocument(); XmlDocumentFragment docfragment = xmldoc.CreateDocumentFragment(); XmlNode subresultnode = xmldoc.CreateElement(Constants.PerfSubResultElement); docfragment.AppendChild(subresultnode); XmlAttribute attrib = xmldoc.CreateAttribute(PerfNameAttribute); attrib.Value = subresultname; subresultnode.Attributes.Append(attrib); string[] perfdataorder = new string[] { "Maximum", "Minimum", "Average", "Elapsed Time", "Number of Iterations" }; for (int i = 0; i < perfdataorder.Length; i++) { string currentperfdata = perfdataorder[i].ToLowerInvariant(); if (perfdatumlist[PerfAverageAttribute] != null) { PerfDatum pd = (PerfDatum)perfdatumlist[PerfAverageAttribute]; if ((int)pd.Value == 0) { return(null); } } IDictionaryEnumerator ide = perfdatumlist.GetEnumerator(); while (ide.MoveNext()) { if (currentperfdata == ide.Key.ToString().ToLowerInvariant()) { XmlNode node = xmldoc.CreateElement(PerfDatumElement); attrib = xmldoc.CreateAttribute(PerfNameAttribute); attrib.Value = ide.Key.ToString(); node.Attributes.Append(attrib); PerfDatum pd = (PerfDatum)ide.Value; //if (perfdataorder[i].ToLowerInvariant() == "average" && // (int)pd.Value == 0) //{ // node = null; // attrib = null; // continue; //} attrib = xmldoc.CreateAttribute(PerfValueAttribute); if (String.IsNullOrEmpty(pd.Unit)) { attrib.Value = ((int)pd.Value).ToString(); } else { attrib.Value = ((int)pd.Value).ToString() + " " + pd.Unit; } node.Attributes.Append(attrib); if (pd.Comparator) { attrib = xmldoc.CreateAttribute(PerfComparatorAttribute); attrib.Value = PerfComparatorYes; node.Attributes.Append(attrib); } subresultnode.AppendChild(node); node = null; attrib = null; break; } } } string outerxml = null; if (comparenode) { subresultnode.AppendChild(xmldoc.CreateComment(projectfilename)); outerxml = subresultnode.InnerXml; } else { outerxml = subresultnode.OuterXml; } subresultnode = null; xmldoc = null; docfragment = null; return(outerxml); }
private void Patch(XmlReader sourceReader, Stream outputStream, XmlDocument diffDoc) { bool bFragments = diffDoc.DocumentElement.GetAttribute("fragments") == "yes"; Encoding enc = null; if (bFragments) { // load fragment XmlDocument tmpDoc = new XmlDocument(); XmlDocumentFragment frag = tmpDoc.CreateDocumentFragment(); XmlNode node; while ((node = tmpDoc.ReadNode(sourceReader)) != null) { switch (node.NodeType) { case XmlNodeType.Whitespace: break; case XmlNodeType.XmlDeclaration: frag.InnerXml = node.OuterXml; break; default: frag.AppendChild(node); break; } if (enc == null) { #if NETCORE enc = Encoding.UTF8; #else if (sourceReader is XmlTextReader) { enc = ((XmlTextReader)sourceReader).Encoding; } else { enc = Encoding.UTF8; } #endif } } // patch XmlNode sourceNode = frag; Patch(ref sourceNode, diffDoc); Debug.Assert(sourceNode == frag); // save if (frag.FirstChild != null && frag.FirstChild.NodeType == XmlNodeType.XmlDeclaration) { enc = Encoding.GetEncoding(((XmlDeclaration)sourceNode.FirstChild).Encoding); } XmlWriter tw = XmlWriter.Create(outputStream, new XmlWriterSettings() { Encoding = enc }); frag.WriteTo(tw); tw.Flush(); } else { // load document XmlDocument sourceDoc = new XmlDocument(); sourceDoc.Load(sourceReader); // patch XmlNode sourceNode = sourceDoc; Patch(ref sourceNode, diffDoc); Debug.Assert(sourceNode == sourceDoc); // save sourceDoc.Save(outputStream); } }
private void Patch(ref XmlNode sourceNode, XmlDocument diffDoc) { XmlElement diffgramEl = diffDoc.DocumentElement; if (diffgramEl.LocalName != "xmldiff" || diffgramEl.NamespaceURI != XmlDiff.NamespaceUri) { XmlPatchError.Error(XmlPatchError.ExpectingDiffgramElement); } XmlNamedNodeMap diffgramAttributes = diffgramEl.Attributes; XmlAttribute srcDocAttr = (XmlAttribute)diffgramAttributes.GetNamedItem("srcDocHash"); if (srcDocAttr == null) { XmlPatchError.Error(XmlPatchError.MissingSrcDocAttribute); } ulong hashValue = 0; try { hashValue = ulong.Parse(srcDocAttr.Value); } catch { XmlPatchError.Error(XmlPatchError.InvalidSrcDocAttribute); } XmlAttribute optionsAttr = (XmlAttribute)diffgramAttributes.GetNamedItem("options"); if (optionsAttr == null) { XmlPatchError.Error(XmlPatchError.MissingOptionsAttribute); } // parse options XmlDiffOptions xmlDiffOptions = XmlDiffOptions.None; try { xmlDiffOptions = XmlDiff.ParseOptions(optionsAttr.Value); } catch { XmlPatchError.Error(XmlPatchError.InvalidOptionsAttribute); } _ignoreChildOrder = ((int)xmlDiffOptions & (int)XmlDiffOptions.IgnoreChildOrder) != 0; // Calculate the hash value of source document and check if it agrees with // of srcDocHash attribute value. if (!XmlDiff.VerifySource(sourceNode, hashValue, xmlDiffOptions)) { XmlPatchError.Error(XmlPatchError.SrcDocMismatch); } // Translate diffgram & Apply patch if (sourceNode.NodeType == XmlNodeType.Document) { Patch patch = CreatePatch(sourceNode, diffgramEl); // create temporary root element and move all document children under it XmlDocument sourceDoc = (XmlDocument)sourceNode; XmlElement tempRoot = sourceDoc.CreateElement("tempRoot"); XmlNode child = sourceDoc.FirstChild; while (child != null) { XmlNode tmpChild = child.NextSibling; if (child.NodeType != XmlNodeType.XmlDeclaration && child.NodeType != XmlNodeType.DocumentType) { sourceDoc.RemoveChild(child); tempRoot.AppendChild(child); } child = tmpChild; } sourceDoc.AppendChild(tempRoot); // Apply patch XmlNode temp = null; patch.Apply(tempRoot, ref temp); // remove the temporary root element if (sourceNode.NodeType == XmlNodeType.Document) { sourceDoc.RemoveChild(tempRoot); Debug.Assert(tempRoot.Attributes.Count == 0); while ((child = tempRoot.FirstChild) != null) { tempRoot.RemoveChild(child); sourceDoc.AppendChild(child); } } } else if (sourceNode.NodeType == XmlNodeType.DocumentFragment) { Patch patch = CreatePatch(sourceNode, diffgramEl); XmlNode temp = null; patch.Apply(sourceNode, ref temp); } else { // create fragment with sourceNode as its only child XmlDocumentFragment fragment = sourceNode.OwnerDocument.CreateDocumentFragment(); XmlNode previousSourceParent = sourceNode.ParentNode; XmlNode previousSourceSibbling = sourceNode.PreviousSibling; if (previousSourceParent != null) { previousSourceParent.RemoveChild(sourceNode); } if (sourceNode.NodeType != XmlNodeType.XmlDeclaration) { fragment.AppendChild(sourceNode); } else { fragment.InnerXml = sourceNode.OuterXml; } Patch patch = CreatePatch(fragment, diffgramEl); XmlNode temp = null; patch.Apply(fragment, ref temp); XmlNodeList childNodes = fragment.ChildNodes; if (childNodes.Count != 1) { XmlPatchError.Error(XmlPatchError.InternalErrorMoreThanOneNodeLeft, childNodes.Count.ToString()); } sourceNode = childNodes.Item(0); fragment.RemoveAll(); if (previousSourceParent != null) { previousSourceParent.InsertAfter(sourceNode, previousSourceSibbling); } } }
static void Main(string[] args) { bool bFragment = false; bool bNodes = false; XmlDiffAlgorithm algorithm = XmlDiffAlgorithm.Auto; try { if (args.Length < 3) { WriteUsage(); return; } XmlDiffOptions options = XmlDiffOptions.None; // process options int curArgsIndex = 0; string optionsString = string.Empty; while (args[curArgsIndex][0] == '/') { if (args[curArgsIndex].Length != 2) { System.Console.Write("Invalid option: " + args[curArgsIndex] + "\n"); return; } switch (args[curArgsIndex][1]) { case 'o': options |= XmlDiffOptions.IgnoreChildOrder; break; case 'c': options |= XmlDiffOptions.IgnoreComments; break; case 'p': options |= XmlDiffOptions.IgnorePI; break; case 'w': options |= XmlDiffOptions.IgnoreWhitespace; break; case 'n': options |= XmlDiffOptions.IgnoreNamespaces; break; case 'r': options |= XmlDiffOptions.IgnorePrefixes; break; case 'x': options |= XmlDiffOptions.IgnoreXmlDecl; break; case 'd': options |= XmlDiffOptions.IgnoreDtd; break; case 'e': bNodes = true; break; case 'f': bFragment = true; break; case 't': algorithm = XmlDiffAlgorithm.Fast; break; case 'z': algorithm = XmlDiffAlgorithm.Precise; break; default: System.Console.Write("Invalid option: " + args[curArgsIndex] + "\n"); return; } optionsString += args[curArgsIndex][1]; curArgsIndex++; if (args.Length - curArgsIndex < 3) { WriteUsage(); return; } } // extract names from command line string sourceXml = args[curArgsIndex]; string targetXml = args[curArgsIndex + 1]; string diffgram = args[curArgsIndex + 2]; bool bVerify = (args.Length - curArgsIndex == 4) && (args[curArgsIndex + 3] == "verify"); // write legend string legend = sourceXml.Substring(sourceXml.LastIndexOf("\\") + 1) + " & " + targetXml.Substring(targetXml.LastIndexOf("\\") + 1) + " -> " + diffgram.Substring(diffgram.LastIndexOf("\\") + 1); if (optionsString != string.Empty) { legend += " (" + optionsString + ")"; } if (legend.Length < 60) { legend += new String(' ', 60 - legend.Length); } else { legend += "\n" + new String(' ', 60); } System.Console.Write(legend); // create diffgram writer XmlWriter DiffgramWriter = new XmlTextWriter(diffgram, new System.Text.UnicodeEncoding()); // create XmlDiff object & set the options XmlDiff xmlDiff = new XmlDiff(options); xmlDiff.Algorithm = algorithm; // compare xml files bool bIdentical; if (bNodes) { if (bFragment) { Console.Write("Cannot have option 'd' and 'f' together."); return; } XmlDocument sourceDoc = new XmlDocument(); sourceDoc.Load(sourceXml); XmlDocument targetDoc = new XmlDocument(); targetDoc.Load(targetXml); bIdentical = xmlDiff.Compare(sourceDoc, targetDoc, DiffgramWriter); } else { bIdentical = xmlDiff.Compare(sourceXml, targetXml, bFragment, DiffgramWriter); } /* * if ( bMeasurePerf ) { * Type type = xmlDiff.GetType(); * MemberInfo[] mi = type.GetMember( "_xmlDiffPerf" ); * if ( mi != null && mi.Length > 0 ) { * XmlDiffPerf xmldiffPerf = (XmlDiffPerf)type.InvokeMember( "_xmlDiffPerf", BindingFlags.GetField, null, xmlDiff, new object[0]); * } * } */ // write result if (bIdentical) { System.Console.Write("identical"); } else { System.Console.Write("different"); } DiffgramWriter.Close(); // verify if (!bIdentical && bVerify) { XmlNode sourceNode; if (bFragment) { NameTable nt = new NameTable(); XmlTextReader tr = new XmlTextReader(new FileStream(sourceXml, FileMode.Open, FileAccess.Read), XmlNodeType.Element, new XmlParserContext(nt, new XmlNamespaceManager(nt), string.Empty, XmlSpace.Default)); XmlDocument doc = new XmlDocument(); XmlDocumentFragment frag = doc.CreateDocumentFragment(); XmlNode node; while ((node = doc.ReadNode(tr)) != null) { if (node.NodeType != XmlNodeType.Whitespace) { frag.AppendChild(node); } } sourceNode = frag; } else { // load source document XmlDocument sourceDoc = new XmlDocument(); sourceDoc.XmlResolver = null; sourceDoc.Load(sourceXml); sourceNode = sourceDoc; } // patch it & save new XmlPatch().Patch(ref sourceNode, new XmlTextReader(diffgram)); if (sourceNode.NodeType == XmlNodeType.Document) { ((XmlDocument)sourceNode).Save("_patched.xml"); } else { XmlTextWriter tw = new XmlTextWriter("_patched.xml", Encoding.Unicode); sourceNode.WriteTo(tw); tw.Close(); } XmlWriter diffgramWriter2 = new XmlTextWriter("_2ndDiff.xml", new System.Text.UnicodeEncoding()); // compare patched source document and target document if (xmlDiff.Compare("_patched.xml", targetXml, bFragment, diffgramWriter2)) { System.Console.Write(" - ok"); } else { System.Console.Write(" - FAILED"); } diffgramWriter2.Close(); } System.Console.Write("\n"); } catch (Exception e) { Console.Write("\n*** Error: " + e.Message + " (source: " + e.Source + ")\n"); } if (System.Diagnostics.Debugger.IsAttached) { Console.Write("\nPress enter...\n"); Console.Read(); } }