private static void TwoTextNodeBase(XmlDocument xmlDocument, InsertType insertType, XmlNodeType nodeType) { XmlNode parent = xmlDocument.DocumentElement; XmlNode refChild = (insertType == InsertType.Prepend) ? parent.FirstChild : parent.LastChild; XmlNode newChild = TestHelper.CreateNode(xmlDocument, nodeType); string original = parent.InnerXml; string expected = (insertType == InsertType.Prepend) ? (newChild.OuterXml + parent.InnerXml) : ((insertType == InsertType.Append) ? (parent.InnerXml + newChild.OuterXml) : (refChild.PreviousSibling.OuterXml + newChild.OuterXml + refChild.OuterXml)); // insert new child var insertDelegate = TestHelper.CreateInsertBeforeOrAfter(insertType); insertDelegate(parent, newChild, refChild); // verify Assert.Equal(3, parent.ChildNodes.Count); Assert.Equal(expected, parent.InnerXml); TestHelper.Verify(parent, refChild, newChild); TestHelper.VerifySiblings(refChild, newChild, insertType); if (insertType == InsertType.Prepend || insertType == InsertType.Append) TestHelper.Verify(refChild, newChild, insertType); // delete new child parent.RemoveChild(newChild); Assert.Equal(2, parent.ChildNodes.Count); TestHelper.VerifySiblings(parent.FirstChild, parent.LastChild, InsertType.Append); Assert.Equal(original, parent.InnerXml); }
private static void VerifyOwnerOfGivenType(XmlNodeType nodeType) { var xmlDocument = new XmlDocument(); var node = xmlDocument.CreateNode(nodeType, "test", string.Empty); Assert.Equal(xmlDocument, node.OwnerDocument); }
/// <summary> /// Adds a new node to the curret XML document. A node is added to XDocument, and another one is added to the XmlTreeNode list that is used by the DevExpress TreeList to visually represent the XML document /// </summary> /// <param name="parrentId"></param> /// <param name="type"></param> public void AddNode(int parrentId, XmlNodeType type) { List<XmlTreeNode> treeNodes = _dataSource.GetXmlTreeNodes(); XmlTreeNode parent = treeNodes.Where(i => i.Id == parrentId).FirstOrDefault(); XElement parentElement = (XElement)parent.XObject; // The default name and value of the new node string name = "Name" + treeNodes.Count; string value = "Value"; // Creates the XObject representing the new node in the XML document XObject newNodeXObject; if (type == XmlNodeType.Element) { newNodeXObject = new XElement(name, value); // When an element becomes a parent, it is no longer allowed to have a value. XDocument does not support parent elements with values if (parentElement.Elements().Count() == 0) parentElement.SetValue(""); } else newNodeXObject = new XAttribute(name, value); parentElement.Add(newNodeXObject); //// Creates the XmlTreeNode that is added to the list of XmlTreeNodes used by the DevExpress TreeList to visually represented the XML document //XmlTreeNode node = new XmlTreeNode() { Id = highestId + 1, ParentId = parrentId, IsParrent = false, Name = "Name" + treeNodes.Count, Value = "Value", Type = type, Parrent = (XElement)parent.XObject, XObject = newNodeXObject }; //treeNodes.Add(node); }
// // Constructors // public CXmlBase(string strPrefix, string strName, string strLocalName, XmlNodeType NodeType, string strNamespace) { _strPrefix = strPrefix; _strName = strName; _strLocalName = strLocalName; _nType = NodeType; _strNamespace = strNamespace; }
protected XPathNavigatorReader(XPathNavigator navToRead) { // Need clone that can be moved independently of original navigator _navToRead = navToRead; _nav = XmlEmptyNavigator.Singleton; _state = State.Initial; _depth = 0; _nodeType = XPathNavigatorReader.ToXmlNodeType(_nav.NodeType); }
public void PositionOnNodeType2(XmlNodeType nodeType) { while (DataReader.Read() && DataReader.NodeType != nodeType) { } if (DataReader.EOF) { throw new CTestFailedException("Couldn't find XmlNodeType " + nodeType); } }
private static void InsertTestBase(string xml, InsertType insertType, XmlNodeType nodeType) { string[] expected = new string[2]; var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(xml); XmlNode parent = xmlDocument.DocumentElement; XmlNode firstChild = parent.FirstChild; XmlNode lastChild = parent.LastChild; XmlNode refChild = parent.FirstChild.NextSibling; XmlNode newChild = TestHelper.CreateNode(xmlDocument, nodeType); expected[0] = parent.InnerXml; expected[1] = (insertType == InsertType.InsertBefore) ? (firstChild.OuterXml + newChild.OuterXml + refChild.OuterXml + lastChild.OuterXml) : (firstChild.OuterXml + refChild.OuterXml + newChild.OuterXml + lastChild.OuterXml); // insertion var insertDelegate = TestHelper.CreateInsertBeforeOrAfter(insertType); insertDelegate(parent, newChild, refChild); // verify Assert.Equal(4, parent.ChildNodes.Count); Assert.Equal(expected[1], parent.InnerXml); TestHelper.Verify(parent, refChild, newChild); TestHelper.Verify(parent, firstChild, lastChild); TestHelper.VerifySiblings(refChild, newChild, insertType); if (insertType == InsertType.InsertBefore) { TestHelper.VerifySiblings(firstChild, newChild, InsertType.Append); TestHelper.VerifySiblings(newChild, refChild, InsertType.Append); TestHelper.VerifySiblings(refChild, lastChild, InsertType.Append); } else { TestHelper.VerifySiblings(firstChild, refChild, InsertType.Append); TestHelper.VerifySiblings(refChild, newChild, InsertType.Append); TestHelper.VerifySiblings(newChild, lastChild, InsertType.Append); } // delete the newChild parent.RemoveChild(newChild); // verify Assert.Equal(3, parent.ChildNodes.Count); Assert.Equal(expected[0], parent.InnerXml); TestHelper.Verify(parent, firstChild, lastChild); TestHelper.VerifySiblings(firstChild, refChild, InsertType.Append); TestHelper.VerifySiblings(refChild, lastChild, InsertType.Append); }
private void VerifyNextNode(XmlNodeType nt, string name, string value) { while (DataReader.NodeType == XmlNodeType.Whitespace || DataReader.NodeType == XmlNodeType.SignificantWhitespace) { // skip all whitespace nodes // if EOF is reached NodeType=None DataReader.Read(); } CError.Compare(DataReader.VerifyNode(nt, name, value), "VerifyNextNode"); }
private static void TwoTextNodeBase(XmlNodeType[] nodeTypes, InsertType insertType, XmlNodeType nodeType) { XmlDocument xmlDocument = new XmlDocument { PreserveWhitespace = true }; var elem = xmlDocument.CreateElement("elem"); xmlDocument.AppendChild(elem); for (int i = 0; i < nodeTypes.Length; i++) elem.AppendChild(TestHelper.CreateNode(xmlDocument, nodeTypes[i])); TwoTextNodeBase(xmlDocument, insertType, nodeType); }
public XsltInput(XmlReader reader, Compiler compiler, KeywordsTable atoms) { Debug.Assert(reader != null); Debug.Assert(atoms != null); EnsureExpandEntities(reader); IXmlLineInfo xmlLineInfo = reader as IXmlLineInfo; this.atoms = atoms; this.reader = reader; this.reatomize = reader.NameTable != atoms.NameTable; this.readerLineInfo = (xmlLineInfo != null && xmlLineInfo.HasLineInfo()) ? xmlLineInfo : null; this.topLevelReader = reader.ReadState == ReadState.Initial; this.scopeManager = new CompilerScopeManager<VarPar>(atoms); this.compiler = compiler; this.nodeType = XmlNodeType.Document; }
protected void TestOnNopNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); string name = DataReader.Name; string value = DataReader.Value; CError.WriteLine("Name=" + name); CError.WriteLine("Value=" + value); if (CheckCanReadBinaryContent()) return; byte[] buffer = new byte[1]; int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1); CError.Compare(nBytes, 0, "nBytes"); CError.Compare(DataReader.VerifyNode(nt, name, value), "vn"); CError.WriteLine("Succeeded:{0}", nt); }
private static void OneTextNodeBase(string xml, InsertType insertType, XmlNodeType nodeType) { var insertDelegate = TestHelper.CreateInsertFrontOrEnd(insertType); var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(xml); var parent = xmlDocument.DocumentElement; var child = parent.FirstChild; var newChild = TestHelper.CreateNode(xmlDocument, nodeType); var expected = (insertType == InsertType.Prepend) ? (newChild.OuterXml + child.OuterXml) : (child.OuterXml + newChild.OuterXml); // insert new child insertDelegate(parent, newChild); // verify Assert.Equal(2, parent.ChildNodes.Count); Assert.Equal(expected, parent.InnerXml); TestHelper.Verify(parent, child, newChild); TestHelper.Verify(child, newChild, insertType); // delete new child parent.RemoveChild(newChild); // verify Assert.Equal(1, parent.ChildNodes.Count); // Verify single child Assert.NotNull(parent); Assert.NotNull(child); Assert.Equal(child, parent.FirstChild); Assert.Equal(child, parent.LastChild); Assert.Null(child.NextSibling); Assert.Null(child.PreviousSibling); // delete the last child parent.RemoveChild(child); // verify Assert.Equal(0, parent.ChildNodes.Count); Assert.Null(parent.FirstChild); Assert.Null(parent.LastChild); Assert.False(parent.HasChildNodes); }
protected void TestOnInvalidNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); if (CheckCanReadBinaryContent()) return; try { byte[] buffer = new byte[1]; int nBytes = DataReader.ReadContentAsBase64(buffer, 0, 1); } catch (InvalidOperationException ioe) { if (ioe.ToString().IndexOf(nt.ToString()) < 0) CError.Compare(false, "Call threw wrong invalid operation exception on " + nt); else return; } CError.Compare(false, "Call succeeded on " + nt); }
protected void TestInvalidNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); string name = DataReader.Name; string value = DataReader.Value; byte[] buffer = new byte[1]; if (CheckCanReadBinaryContent()) return; try { int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } CError.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); }
private static void OneTextNode_OneNonTextNodeBase(string xml, InsertType insertType, XmlNodeType nodeType, bool deleteFirst) { var xmlDocument = new XmlDocument { PreserveWhitespace = true }; xmlDocument.LoadXml(xml); XmlNode parent = xmlDocument.DocumentElement; XmlNode refChild = (insertType == InsertType.Prepend) ? parent.FirstChild : parent.LastChild; XmlNode newChild = TestHelper.CreateNode(xmlDocument, nodeType); XmlNode nodeToRemove = (deleteFirst) ? parent.FirstChild : parent.LastChild; // populate the expected result, where expected[0] is the expected result after insertion, and expected[1] is the expected result after deletion string[] expected = new string[2]; expected[0] = (insertType == InsertType.Prepend) ? (newChild.OuterXml + parent.InnerXml) : ((insertType == InsertType.Append) ? (parent.InnerXml + newChild.OuterXml) : (refChild.PreviousSibling.OuterXml + newChild.OuterXml + refChild.OuterXml)); if (deleteFirst) expected[1] = (insertType == InsertType.Append) ? (parent.LastChild.OuterXml + newChild.OuterXml) : (newChild.OuterXml + parent.LastChild.OuterXml); else expected[1] = (insertType == InsertType.Prepend) ? (newChild.OuterXml + parent.FirstChild.OuterXml) : (parent.FirstChild.OuterXml + newChild.OuterXml); // insert new child var insertDelegate = TestHelper.CreateInsertBeforeOrAfter(insertType); insertDelegate(parent, newChild, refChild); // verify Assert.Equal(3, parent.ChildNodes.Count); Assert.Equal(expected[0], parent.InnerXml); TestHelper.Verify(parent, refChild, newChild); TestHelper.VerifySiblings(refChild, newChild, insertType); if (insertType == InsertType.Prepend || insertType == InsertType.Append) TestHelper.Verify(refChild, newChild, insertType); // delete new child parent.RemoveChild(nodeToRemove); Assert.Equal(2, parent.ChildNodes.Count); TestHelper.VerifySiblings(parent.FirstChild, parent.LastChild, InsertType.Append); Assert.Equal(expected[1], parent.InnerXml); }
public static XmlNode CreateNode(XmlDocument doc, XmlNodeType nodeType) { Assert.NotNull(doc); switch (nodeType) { case XmlNodeType.CDATA: return doc.CreateCDataSection(@"< & <tag> < ! > & </tag> "); case XmlNodeType.Comment: return doc.CreateComment(@"comment"); case XmlNodeType.Element: return doc.CreateElement("E"); case XmlNodeType.Text: return doc.CreateTextNode("text"); case XmlNodeType.Whitespace: return doc.CreateWhitespace(@" "); case XmlNodeType.SignificantWhitespace: return doc.CreateSignificantWhitespace(" "); default: throw new ArgumentException("Wrong XmlNodeType: '" + nodeType + "'"); } }
private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle, List <string> xamlAncestors, List <string> htmlAncestors) { bool flag = false; if (xamlReader.IsEmptyElement) { if (htmlWriter != null && !flag && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); inlineStyle.Remove(0, inlineStyle.Length); } return; } while (HtmlFromXamlConverter.ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement) { XmlNodeType nodeType = xamlReader.NodeType; switch (nodeType) { case XmlNodeType.Element: if (xamlReader.Name.Contains(".") && xamlReader.Name != "Table.Columns") { HtmlFromXamlConverter.AddComplexProperty(xamlReader, inlineStyle, xamlAncestors, htmlAncestors); continue; } if (htmlWriter != null && !flag && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); inlineStyle.Remove(0, inlineStyle.Length); } flag = true; HtmlFromXamlConverter.WriteElement(xamlReader, htmlWriter, inlineStyle, xamlAncestors, htmlAncestors); continue; case XmlNodeType.Attribute: case XmlNodeType.Entity: case XmlNodeType.ProcessingInstruction: continue; case XmlNodeType.Text: case XmlNodeType.CDATA: break; case XmlNodeType.EntityReference: if (htmlWriter != null) { htmlWriter.WriteRaw(" "); } flag = true; continue; case XmlNodeType.Comment: if (htmlWriter != null) { if (!flag && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); } htmlWriter.WriteComment(xamlReader.Value); } flag = true; continue; default: if (nodeType != XmlNodeType.SignificantWhitespace) { continue; } break; } if (htmlWriter != null) { if (!flag && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); } if (xamlReader.NodeType == XmlNodeType.SignificantWhitespace) { for (int i = 0; i < xamlReader.Value.Length; i++) { if (xamlReader.Value[i] == ' ') { htmlWriter.WriteRaw(" "); } else { htmlWriter.WriteString(xamlReader.Value[i].ToString()); } } } else { htmlWriter.WriteString(xamlReader.Value); } } flag = true; } }
public static void ReadXml() { while (reader.Read()) { node = reader.NodeType; if (node == XmlNodeType.Element) { switch (reader.Name) { case "browser": reader.Read(); browser = reader.Value; break; case "url": reader.Read(); url = reader.Value; break; case "language": reader.Read(); lang = reader.Value; break; case "implicitWait": reader.Read(); implicitWait = int.Parse(reader.Value); break; case "filename": reader.Read(); filename = reader.Value; break; case "year": reader.Read(); year = reader.Value; break; case "culture": reader.Read(); culture = reader.Value; break; case "pageLoadTime": reader.Read(); pageLoadTime = int.Parse(reader.Value); break; case "implicitForPage": reader.Read(); implicitForPage = int.Parse(reader.Value); break; case "scriptPath": reader.Read(); scriptPath = @reader.Value; break; case "taskDelay": reader.Read(); taskDelay = int.Parse(reader.Value); break; case "countLoop": reader.Read(); countLoop = int.Parse(reader.Value); break; } } } reader.Close(); }
// Token: 0x060009A1 RID: 2465 RVA: 0x00044B48 File Offset: 0x00042D48 private void ParseElementClass(string experience, ApplicationElement applicationElement) { ExTraceGlobals.FormsRegistryCallTracer.TraceDebug((long)this.GetHashCode(), "FormsRegistryParser.ParseElementClass"); bool flag = false; string itemClass = string.Empty; if (this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[14])) { itemClass = this.reader.Value; } ulong num = 0UL; if (this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[18])) { num = this.ParseRequiredFeatures(this.reader.Value); } while (!flag && this.reader.Read()) { XmlNodeType nodeType = this.reader.NodeType; if (nodeType != XmlNodeType.Element) { if (nodeType == XmlNodeType.EndElement) { if (this.reader.Name == FormsRegistryParser.nameTableValues[12]) { flag = true; } } } else { if (this.reader.Name == FormsRegistryParser.nameTableValues[13]) { string text = string.Empty; string action = string.Empty; string state = string.Empty; ulong segmentationFlags = num; if (this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[16])) { action = this.reader.Value; } if (this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[17])) { state = this.reader.Value; } if (this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[18])) { segmentationFlags = this.ParseRequiredFeatures(this.reader.Value); } if (!this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[15])) { this.ThrowExpectedAttributeException(FormsRegistryParser.NameTableValues.Form); } text = this.reader.Value; FormKey formKey = new FormKey(experience, applicationElement, itemClass, action, state); ExTraceGlobals.FormsRegistryDataTracer.TraceDebug <FormKey, string>((long)this.GetHashCode(), "Parsed Mapping - key = ({0}), form = {1}", formKey, text); try { if (applicationElement == ApplicationElement.PreFormAction) { this.registry.AddPreForm(formKey, text, segmentationFlags); } else { this.registry.AddForm(formKey, text, segmentationFlags); } continue; } catch (OwaInvalidInputException ex) { OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_FormsRegistryParseError, ex.Message, new object[] { this.registryFile, this.reader.LineNumber.ToString(CultureInfo.InvariantCulture), this.reader.LinePosition.ToString(CultureInfo.InvariantCulture), ex.Message }); throw ex; } } this.ThrowExpectedElementException(FormsRegistryParser.NameTableValues.Mapping); } } }
/// <summary> /// Displays XML in the main rich text box. /// </summary> /// <param name="xml">XML to display.</param> private void DisplayXml(string xml) { //clear text _xmlRichTextBox.Text = ""; //stop redrawing User32Api.SendMessage(_xmlRichTextBox.Handle, User32Api.WM_SETREDRAW, 0, IntPtr.Zero); //if we have some xml, display it if (xml != null && xml.Length > 0) { StringReader sr = null; try { //create a new bold font Font standardFont = _xmlRichTextBox.SelectionFont; Font boldFont = new Font(standardFont.Name, standardFont.Size, (FontStyle)((int)standardFont.Style + (int)FontStyle.Bold)); //load xml into a text reader XmlTextReader reader = null; sr = new StringReader(xml); reader = new XmlTextReader(sr); int tabCount = -1; XmlNodeType previousNodeType = XmlNodeType.XmlDeclaration; bool previousElementEmpty = false; //itterate thru the XML, drawing out while (reader.Read()) { //figure out if we need to start a new line, and configure the tabcount bool isNewLineRequired = false; if (previousNodeType == XmlNodeType.EndElement || previousElementEmpty) //(previousElementEmpty && reader.NodeType == XmlNodeType.EndElement) { tabCount--; } if (reader.NodeType != XmlNodeType.XmlDeclaration) { if (reader.IsStartElement()) { tabCount++; if (tabCount > 0) { isNewLineRequired = true; } } else if (previousNodeType == XmlNodeType.EndElement || previousElementEmpty) { isNewLineRequired = true; } //if necessary, create a new line if (isNewLineRequired) { _xmlRichTextBox.SelectedText = "\n" + GetIndentString(tabCount); } } previousElementEmpty = false; //write the XML node switch (reader.NodeType) { //TODO validate workings of entities, notations case XmlNodeType.Document: case XmlNodeType.DocumentFragment: case XmlNodeType.DocumentType: case XmlNodeType.Entity: case XmlNodeType.EndEntity: case XmlNodeType.EntityReference: case XmlNodeType.Notation: case XmlNodeType.XmlDeclaration: _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; _xmlRichTextBox.SelectedText = string.Format("<{0}/>\n", reader.Value); break; case XmlNodeType.Element: _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; _xmlRichTextBox.SelectedText = "<"; _xmlRichTextBox.SelectionColor = _xmlColours.ElementName; _xmlRichTextBox.SelectedText = reader.Name; bool isEmptyElement = reader.IsEmptyElement; while (reader.MoveToNextAttribute()) { _xmlRichTextBox.SelectionColor = _xmlColours.AttributeName; _xmlRichTextBox.SelectedText = " " + reader.Name; _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; _xmlRichTextBox.SelectedText = "=\""; _xmlRichTextBox.SelectionColor = _xmlColours.AttributeValue; _xmlRichTextBox.SelectionFont = boldFont; _xmlRichTextBox.SelectedText = reader.Value; _xmlRichTextBox.SelectionFont = standardFont; _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; _xmlRichTextBox.SelectedText = "\""; } _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; if (isEmptyElement) { _xmlRichTextBox.SelectedText = " /"; previousElementEmpty = true; } _xmlRichTextBox.SelectedText = ">"; break; case XmlNodeType.Text: _xmlRichTextBox.SelectionColor = _xmlColours.ElementValue; _xmlRichTextBox.SelectionFont = boldFont; _xmlRichTextBox.SelectedText = reader.Value; _xmlRichTextBox.SelectionFont = standardFont; break; case XmlNodeType.EndElement: _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; _xmlRichTextBox.SelectedText = "</"; _xmlRichTextBox.SelectionColor = _xmlColours.ElementName; _xmlRichTextBox.SelectedText = reader.Name; _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; _xmlRichTextBox.SelectedText = ">"; break; case XmlNodeType.CDATA: _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; _xmlRichTextBox.SelectedText = "<![CDATA["; _xmlRichTextBox.SelectionColor = _xmlColours.ElementValue; _xmlRichTextBox.SelectionFont = boldFont; _xmlRichTextBox.SelectedText = reader.Value; _xmlRichTextBox.SelectionFont = standardFont; _xmlRichTextBox.SelectionColor = _xmlColours.SpecialCharacter; _xmlRichTextBox.SelectedText = "]]>"; break; } //store the current node for later use previousNodeType = reader.NodeType; } //tidy up and position the cursor _xmlRichTextBox.SelectedText = "\n"; _xmlRichTextBox.Select(0, 0); } catch { _xmlRichTextBox.Text = xml; } finally { if (sr != null) { sr.Close(); } } } //stop redrawing User32Api.SendMessage(_xmlRichTextBox.Handle, User32Api.WM_SETREDRAW, 1, IntPtr.Zero); _xmlRichTextBox.Refresh(); }
private bool LoadFile(Stream stream, SvgTestInfo testInfo) { testDetailsDoc.Blocks.Clear(); Regex rgx = new Regex("\\s+"); testTitle.Text = testInfo.Title; testDescrition.Text = rgx.Replace(testInfo.Description, " ").Trim(); testFilePath.Text = _svgFilePath; btnFilePath.IsEnabled = true; XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = false; settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.DtdProcessing = DtdProcessing.Parse; settings.XmlResolver = null; SvgTestSuite selectedTestSuite = null; if (_optionSettings != null) { selectedTestSuite = _optionSettings.SelectedTestSuite; } if (selectedTestSuite == null) { selectedTestSuite = SvgTestSuite.GetDefault(SvgTestSuite.Create()); } int majorVersion = selectedTestSuite.MajorVersion; int minorVersion = selectedTestSuite.MinorVersion; using (XmlReader reader = XmlReader.Create(stream, settings)) { if (majorVersion == 1 && minorVersion == 1) { if (reader.ReadToFollowing("d:SVGTestCase")) { _testCase = new SvgTestCase(); while (reader.Read()) { string nodeName = reader.Name; XmlNodeType nodeType = reader.NodeType; if (nodeType == XmlNodeType.Element) { if (string.Equals(nodeName, "d:operatorScript", StringComparison.OrdinalIgnoreCase)) { string inputText = reader.ReadInnerXml(); string xamlText = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false); Paragraph titlePara = new Paragraph(); titlePara.FontWeight = FontWeights.Bold; titlePara.FontSize = 16; titlePara.Inlines.Add(new Run("Operator Script")); if (_useConverter) { StringReader stringReader = new StringReader(xamlText); XmlReader xmlReader = XmlReader.Create(stringReader); Section nextSection = (Section)XamlReader.Load(xmlReader); if (nextSection != null) { testDetailsDoc.Blocks.Add(titlePara); testDetailsDoc.Blocks.Add(nextSection); } } else { Section pageSession = new Section(); Paragraph nextPara = new Paragraph(); //nextPara.Padding = new Thickness(3, 5, 3, 5); string paraText = rgx.Replace(inputText, " ").Trim(); nextPara.Inlines.Add(new Run(paraText)); pageSession.Blocks.Add(titlePara); pageSession.Blocks.Add(nextPara); testDetailsDoc.Blocks.Add(pageSession); } } else if (string.Equals(nodeName, "d:passCriteria", StringComparison.OrdinalIgnoreCase)) { string inputText = reader.ReadInnerXml(); string xamlText = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false); Paragraph titlePara = new Paragraph(); titlePara.FontWeight = FontWeights.Bold; titlePara.FontSize = 16; titlePara.Inlines.Add(new Run("Pass Criteria")); if (_useConverter) { StringReader stringReader = new StringReader(xamlText); XmlReader xmlReader = XmlReader.Create(stringReader); Section nextSection = (Section)XamlReader.Load(xmlReader); if (nextSection != null) { testDetailsDoc.Blocks.Add(titlePara); testDetailsDoc.Blocks.Add(nextSection); } } else { Section pageSession = new Section(); Paragraph nextPara = new Paragraph(); //nextPara.Padding = new Thickness(3, 5, 3, 5); string paraText = rgx.Replace(inputText, " ").Trim(); nextPara.Inlines.Add(new Run(paraText)); pageSession.Blocks.Add(titlePara); pageSession.Blocks.Add(nextPara); testDetailsDoc.Blocks.Add(pageSession); } } else if (string.Equals(nodeName, "d:testDescription", StringComparison.OrdinalIgnoreCase)) { string inputText = reader.ReadInnerXml(); string xamlText = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false); Paragraph titlePara = new Paragraph(); titlePara.FontWeight = FontWeights.Bold; titlePara.FontSize = 16; titlePara.Inlines.Add(new Run("Test Description")); if (_useConverter) { StringReader stringReader = new StringReader(xamlText); XmlReader xmlReader = XmlReader.Create(stringReader); Section nextSection = (Section)XamlReader.Load(xmlReader); if (nextSection != null) { testDetailsDoc.Blocks.Add(titlePara); testDetailsDoc.Blocks.Add(nextSection); } } else { Section pageSession = new Section(); Paragraph nextPara = new Paragraph(); //nextPara.Padding = new Thickness(3, 5, 3, 5); string paraText = rgx.Replace(inputText, " ").Trim(); nextPara.Inlines.Add(new Run(paraText)); pageSession.Blocks.Add(titlePara); pageSession.Blocks.Add(nextPara); testDetailsDoc.Blocks.Add(pageSession); } _testCase.Paragraphs.Add(inputText); } } else if (nodeType == XmlNodeType.EndElement && string.Equals(nodeName, "SVGTestCase", StringComparison.OrdinalIgnoreCase)) { break; } } } } else if (majorVersion == 1 && minorVersion == 2) { if (reader.ReadToFollowing("SVGTestCase")) { _testCase = new SvgTestCase(); while (reader.Read()) { string nodeName = reader.Name; XmlNodeType nodeType = reader.NodeType; if (nodeType == XmlNodeType.Element) { if (string.Equals(nodeName, "d:OperatorScript", StringComparison.OrdinalIgnoreCase)) { string inputText = reader.ReadInnerXml(); string xamlText = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false); if (_useConverter) { StringReader stringReader = new StringReader(xamlText); XmlReader xmlReader = XmlReader.Create(stringReader); Section nextSection = (Section)XamlReader.Load(xmlReader); if (nextSection != null) { testDetailsDoc.Blocks.Add(nextSection); } } else { Section pageSession = new Section(); Paragraph nextPara = new Paragraph(); //nextPara.Padding = new Thickness(3, 5, 3, 5); string paraText = rgx.Replace(inputText, " ").Trim(); nextPara.Inlines.Add(new Run(paraText)); pageSession.Blocks.Add(nextPara); testDetailsDoc.Blocks.Add(pageSession); } } else if (string.Equals(nodeName, "d:PassCriteria", StringComparison.OrdinalIgnoreCase)) { string inputText = reader.ReadInnerXml(); string xamlText = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false); if (_useConverter) { StringReader stringReader = new StringReader(xamlText); XmlReader xmlReader = XmlReader.Create(stringReader); Section nextSection = (Section)XamlReader.Load(xmlReader); if (nextSection != null) { testDetailsDoc.Blocks.Add(nextSection); } } else { Section pageSession = new Section(); Paragraph nextPara = new Paragraph(); //nextPara.Padding = new Thickness(3, 5, 3, 5); string paraText = rgx.Replace(inputText, " ").Trim(); nextPara.Inlines.Add(new Run(paraText)); pageSession.Blocks.Add(nextPara); testDetailsDoc.Blocks.Add(pageSession); } } else if (string.Equals(nodeName, "d:TestDescription", StringComparison.OrdinalIgnoreCase)) { string inputText = reader.ReadInnerXml(); string xamlText = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false); if (_useConverter) { StringReader stringReader = new StringReader(xamlText); XmlReader xmlReader = XmlReader.Create(stringReader); Section nextSection = (Section)XamlReader.Load(xmlReader); if (nextSection != null) { testDetailsDoc.Blocks.Add(nextSection); } } else { Section pageSession = new Section(); Paragraph nextPara = new Paragraph(); //nextPara.Padding = new Thickness(3, 5, 3, 5); string paraText = rgx.Replace(inputText, " ").Trim(); nextPara.Inlines.Add(new Run(paraText)); pageSession.Blocks.Add(nextPara); testDetailsDoc.Blocks.Add(pageSession); } _testCase.Paragraphs.Add(inputText); } } else if (nodeType == XmlNodeType.EndElement && string.Equals(nodeName, "SVGTestCase", StringComparison.OrdinalIgnoreCase)) { break; } } } } else { if (reader.ReadToFollowing("SVGTestCase")) { _testCase = new SvgTestCase(); while (reader.Read()) { string nodeName = reader.Name; XmlNodeType nodeType = reader.NodeType; if (nodeType == XmlNodeType.Element) { if (string.Equals(nodeName, "OperatorScript", StringComparison.OrdinalIgnoreCase)) { string revisionText = reader.GetAttribute("version"); if (!string.IsNullOrWhiteSpace(revisionText)) { revisionText = revisionText.Replace("$", string.Empty); _testCase.Revision = revisionText.Trim(); } string nameText = reader.GetAttribute("testname"); if (!string.IsNullOrWhiteSpace(nameText)) { _testCase.Name = nameText.Trim(); } } else if (string.Equals(nodeName, "Paragraph", StringComparison.OrdinalIgnoreCase)) { string inputText = reader.ReadInnerXml(); string xamlText = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(inputText, false); if (_useConverter) { StringReader stringReader = new StringReader(xamlText); XmlReader xmlReader = XmlReader.Create(stringReader); Section nextSection = (Section)XamlReader.Load(xmlReader); testDetailsDoc.Blocks.Add(nextSection); } else { Section pageSession = new Section(); Paragraph nextPara = new Paragraph(); //nextPara.Padding = new Thickness(3, 5, 3, 5); string paraText = rgx.Replace(inputText, " ").Trim(); nextPara.Inlines.Add(new Run(paraText)); pageSession.Blocks.Add(nextPara); testDetailsDoc.Blocks.Add(pageSession); } _testCase.Paragraphs.Add(inputText); } } else if (nodeType == XmlNodeType.EndElement && string.Equals(nodeName, "SVGTestCase", StringComparison.OrdinalIgnoreCase)) { break; } } } } } SubscribeToAllHyperlinks(); return(true); }
internal XmlDiffViewCharData(string value, XmlNodeType nodeType) : base(nodeType) { this._value = value; }
/// <summary> /// Moves to the element that contains the current attribute node. /// </summary> /// <returns> /// <c>true</c> if the reader is positioned on an attribute (the reader moves to the element that owns the attribute); <c>false</c> if the reader is not positioned on an attribute (the position of the reader does not change). /// </returns> public override bool MoveToElement() { _attrs = null; _node = XmlNodeType.Element; return(true); }
public virtual object Create(object parent, object configContext, XmlNode section) { IWebProxy result = parent as IWebProxy; #if (XML_DEP) if (section.Attributes != null && section.Attributes.Count != 0) { HandlersUtil.ThrowException("Unrecognized attribute", section); } XmlNodeList nodes = section.ChildNodes; foreach (XmlNode child in nodes) { XmlNodeType ntype = child.NodeType; if (ntype == XmlNodeType.Whitespace || ntype == XmlNodeType.Comment) { continue; } if (ntype != XmlNodeType.Element) { HandlersUtil.ThrowException("Only elements allowed", child); } string name = child.Name; if (name == "proxy") { string sysdefault = HandlersUtil.ExtractAttributeValue("usesystemdefault", child, true); string bypass = HandlersUtil.ExtractAttributeValue("bypassonlocal", child, true); string address = HandlersUtil.ExtractAttributeValue("proxyaddress", child, true); if (child.Attributes != null && child.Attributes.Count != 0) { HandlersUtil.ThrowException("Unrecognized attribute", child); } result = new WebProxy(); bool bp = (bypass != null && String.Compare(bypass, "true", true) == 0); if (bp == false) { if (bypass != null && String.Compare(bypass, "false", true) != 0) { HandlersUtil.ThrowException("Invalid boolean value", child); } } if (!(result is WebProxy)) { continue; } ((WebProxy)result).BypassProxyOnLocal = bp; if (address != null) { try { ((WebProxy)result).Address = new Uri(address); continue; } catch (UriFormatException) {} //MS: ignore bad URIs, fall through to default } //MS: presence of valid address URI takes precedence over usesystemdefault if (sysdefault != null && String.Compare(sysdefault, "true", true) == 0) { address = Environment.GetEnvironmentVariable("http_proxy"); if (address == null) { address = Environment.GetEnvironmentVariable("HTTP_PROXY"); } if (address != null) { try { Uri uri = new Uri(address); IPAddress ip; if (IPAddress.TryParse(uri.Host, out ip)) { if (IPAddress.Any.Equals(ip)) { UriBuilder builder = new UriBuilder(uri); builder.Host = "127.0.0.1"; uri = builder.Uri; } else if (IPAddress.IPv6Any.Equals(ip)) { UriBuilder builder = new UriBuilder(uri); builder.Host = "[::1]"; uri = builder.Uri; } } ((WebProxy)result).Address = uri; } catch (UriFormatException) { } } } continue; } if (name == "bypasslist") { if (!(result is WebProxy)) { continue; } FillByPassList(child, (WebProxy)result); continue; } if (name == "module") { HandlersUtil.ThrowException("WARNING: module not implemented yet", child); } HandlersUtil.ThrowException("Unexpected element", child); } #endif return(result); }
private int ReadTextNodes() { bool textPreserveWS = _reader.XmlSpace == XmlSpace.Preserve; bool textIsWhite = true; int curTextNode = 0; do { switch (_reader.NodeType) { case XmlNodeType.Text: // XLinq reports WS nodes as Text so we need to analyze them here case XmlNodeType.CDATA: if (textIsWhite && !XmlCharType.Instance.IsOnlyWhitespace(_reader.Value)) { textIsWhite = false; } goto case XmlNodeType.SignificantWhitespace; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: ExtendRecordBuffer(curTextNode); FillupTextRecord(ref _records[curTextNode]); _reader.Read(); curTextNode++; break; case XmlNodeType.EntityReference: string local = _reader.LocalName; if (local.Length > 0 && ( local[0] == '#' || local == "lt" || local == "gt" || local == "quot" || local == "apos" )) { // Special treatment for character and built-in entities ExtendRecordBuffer(curTextNode); FillupCharacterEntityRecord(ref _records[curTextNode]); if (textIsWhite && !XmlCharType.Instance.IsOnlyWhitespace(_records[curTextNode].value)) { textIsWhite = false; } curTextNode++; } else { _reader.ResolveEntity(); _reader.Read(); } break; case XmlNodeType.EndEntity: _reader.Read(); break; default: _nodeType = ( !textIsWhite ? XmlNodeType.Text : textPreserveWS ? XmlNodeType.SignificantWhitespace : /*default: */ XmlNodeType.Whitespace ); return(curTextNode); } } while (true); }
public virtual object Create(object parent, object configContext, XmlNode section) { ConnectionManagementData cmd = new ConnectionManagementData(parent); #if (XML_DEP) if (section.Attributes != null && section.Attributes.Count != 0) { HandlersUtil.ThrowException("Unrecognized attribute", section); } XmlNodeList httpHandlers = section.ChildNodes; foreach (XmlNode child in httpHandlers) { XmlNodeType ntype = child.NodeType; if (ntype == XmlNodeType.Whitespace || ntype == XmlNodeType.Comment) { continue; } if (ntype != XmlNodeType.Element) { HandlersUtil.ThrowException("Only elements allowed", child); } string name = child.Name; if (name == "clear") { if (child.Attributes != null && child.Attributes.Count != 0) { HandlersUtil.ThrowException("Unrecognized attribute", child); } cmd.Clear(); continue; } //LAMESPEC: the MS doc says that <remove name="..."/> but they throw an exception // if you use that. "address" is correct. string address = HandlersUtil.ExtractAttributeValue("address", child); if (name == "add") { string maxcnc = HandlersUtil.ExtractAttributeValue("maxconnection", child, true); if (child.Attributes != null && child.Attributes.Count != 0) { HandlersUtil.ThrowException("Unrecognized attribute", child); } cmd.Add(address, maxcnc); continue; } if (name == "remove") { if (child.Attributes != null && child.Attributes.Count != 0) { HandlersUtil.ThrowException("Unrecognized attribute", child); } cmd.Remove(address); continue; } HandlersUtil.ThrowException("Unexpected element", child); } #endif return(cmd); }
protected internal override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) { string ElementName = reader.Name; base.DeserializeElement(reader, serializeCollectionKey); if ((File != null) && (File.Length > 0)) { string sourceFileFullPath; string configFileDirectory; string configFile; // Determine file location configFile = ElementInformation.Source; if (String.IsNullOrEmpty(configFile)) { sourceFileFullPath = File; } else { configFileDirectory = System.IO.Path.GetDirectoryName(configFile); sourceFileFullPath = System.IO.Path.Combine(configFileDirectory, File); } if (System.IO.File.Exists(sourceFileFullPath)) { int lineOffset = 0; string rawXml = null; using (Stream sourceFileStream = new FileStream(sourceFileFullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (XmlUtil xmlUtil = new XmlUtil(sourceFileStream, sourceFileFullPath, true)) { if (xmlUtil.Reader.Name != ElementName) { throw new ConfigurationErrorsException( SR.GetString(SR.Config_name_value_file_section_file_invalid_root, ElementName), xmlUtil); } lineOffset = xmlUtil.Reader.LineNumber; rawXml = xmlUtil.CopySection(); // Detect if there is any XML left over after the section while (!xmlUtil.Reader.EOF) { XmlNodeType t = xmlUtil.Reader.NodeType; if (t != XmlNodeType.Comment) { throw new ConfigurationErrorsException(SR.GetString(SR.Config_source_file_format), xmlUtil); } xmlUtil.Reader.Read(); } } } ConfigXmlReader internalReader = new ConfigXmlReader(rawXml, sourceFileFullPath, lineOffset); internalReader.Read(); if (internalReader.MoveToNextAttribute()) { throw new ConfigurationErrorsException(SR.GetString(SR.Config_base_unrecognized_attribute, internalReader.Name), (XmlReader)internalReader); } internalReader.MoveToElement(); base.DeserializeElement(internalReader, serializeCollectionKey); } } }
///<summary> /// Constructor. ///</summary> public Difference(DifferenceType id, XmlNodeType controlNodeType, XmlNodeType testNodeType) : this(id) { _controlNodeType = controlNodeType; _testNodeType = testNodeType; }
static string DiffXml( int nLevel, string strOldFragmentXml, XmlNodeType old_nodetype, string strNewFragmentXml, XmlNodeType new_nodetype) { if (string.IsNullOrEmpty(strOldFragmentXml) == true && string.IsNullOrEmpty(strNewFragmentXml) == true) { return(""); } if (old_nodetype != XmlNodeType.Element || new_nodetype != XmlNodeType.Element) { if (old_nodetype == XmlNodeType.Element) { strOldFragmentXml = GetIndentXml(strOldFragmentXml); } if (new_nodetype == XmlNodeType.Element) { strNewFragmentXml = GetIndentXml(strNewFragmentXml); } return(GetPlanTextDiffHtml( nLevel, strOldFragmentXml, strNewFragmentXml)); } string strOldChildren = ""; string strOldBegin = ""; string strOldEnd = ""; List <XmlNode> old_childnodes = null; string strOldElementName = ""; GetComparableXmlString(strOldFragmentXml, out strOldChildren, out old_childnodes, out strOldElementName, out strOldBegin, out strOldEnd); string strNewChildren = ""; string strNewBegin = ""; string strNewEnd = ""; List <XmlNode> new_childnodes = null; string strNewElementName = ""; GetComparableXmlString(strNewFragmentXml, out strNewChildren, out new_childnodes, out strNewElementName, out strNewBegin, out strNewEnd); bool bSpecialCompare = false; // 是否属于特殊情况: 根元素名不相同,但仍需要比较下级 if (strOldElementName != strNewElementName && nLevel == 0) { bSpecialCompare = true; } if (strOldElementName != strNewElementName && bSpecialCompare == false) { // 元素名不一样了并且不是根级别,就没有必要做细节比较了 // 意思是说如果是根级别,即便根元素名不一样,也要比较其下级 if (old_nodetype == XmlNodeType.Element) { strOldFragmentXml = GetIndentXml(strOldFragmentXml); } if (new_nodetype == XmlNodeType.Element) { strNewFragmentXml = GetIndentXml(strNewFragmentXml); } return(GetPlanTextDiffHtml( nLevel, strOldFragmentXml, strNewFragmentXml)); } string strLineClass = "datafield"; StringBuilder strResult = new StringBuilder(4096); if (nLevel > 0 || bSpecialCompare == true) { ChangeType begin_type = ChangeType.Unchanged; if (strOldBegin != strNewBegin) { begin_type = ChangeType.Modified; } // Begin strResult.Append("\r\n<tr class='" + strLineClass + "'>"); strResult.Append(BuildFragmentFieldHtml(nLevel, begin_type, strOldBegin)); strResult.Append(SEP); strResult.Append(BuildFragmentFieldHtml(nLevel, begin_type, strNewBegin)); strResult.Append("\r\n</tr>"); } // return "\r\n<td class='content' colspan='3'></td>"; if (string.IsNullOrEmpty(strOldChildren) == false || string.IsNullOrEmpty(strNewChildren) == false) { var xml_differ = new Differ(); var xml_builder = new SideBySideDiffBuilder(xml_differ); var xml_diff_result = xml_builder.BuildDiffModel(strOldChildren, strNewChildren); Debug.Assert(xml_diff_result.OldText.Lines.Count == xml_diff_result.NewText.Lines.Count, ""); int old_index = 0; int new_index = 0; for (int index = 0; index < xml_diff_result.NewText.Lines.Count; index++) { var newline = xml_diff_result.NewText.Lines[index]; var oldline = xml_diff_result.OldText.Lines[index]; XmlNode new_node = null; if (newline.Type != ChangeType.Imaginary) { new_node = new_childnodes[new_index++]; } XmlNode old_node = null; if (oldline.Type != ChangeType.Imaginary) { old_node = old_childnodes[old_index++]; } if (newline.Type == ChangeType.Modified) { strResult.Append(DiffXml(nLevel + 1, oldline.Text, old_node.NodeType, newline.Text, new_node.NodeType)); continue; } string strOldText = ""; if (old_node != null && old_node.NodeType == XmlNodeType.Element) { strOldText = GetIndentXml(oldline.Text); } else { strOldText = oldline.Text; } string strNewText = ""; if (new_node != null && new_node.NodeType == XmlNodeType.Element) { strNewText = GetIndentXml(newline.Text); } else { strNewText = newline.Text; } strResult.Append("\r\n<tr class='" + strLineClass + "'>"); // 创建一个 XML 字段的 HTML 局部 三个 <td> strResult.Append(BuildFragmentFieldHtml(nLevel + 1, oldline.Type, strOldText)); strResult.Append(SEP); strResult.Append(BuildFragmentFieldHtml(nLevel + 1, newline.Type, strNewText)); strResult.Append("\r\n</tr>"); } } if (nLevel > 0 || bSpecialCompare == true) { ChangeType end_type = ChangeType.Unchanged; if (strOldEnd != strNewEnd) { end_type = ChangeType.Modified; } // End strResult.Append("\r\n<tr class='" + strLineClass + "'>"); strResult.Append(BuildFragmentFieldHtml(nLevel, end_type, strOldEnd)); strResult.Append(SEP); strResult.Append(BuildFragmentFieldHtml(nLevel, end_type, strNewEnd)); strResult.Append("\r\n</tr>"); } return(strResult.ToString()); }
private void TryIndent(TextArea textArea, int begin, int end) { string str1 = ""; Stack stack = new Stack(); IDocument document = textArea.Document; string indentationString = Tab.GetIndentationString(document); int lineNumber1 = begin; int x = 0; bool flag = false; XmlNodeType xmlNodeType = XmlNodeType.XmlDeclaration; XmlTextReader xmlTextReader = (XmlTextReader)null; using (StringReader stringReader = new StringReader(document.TextContent)) { try { xmlTextReader = new XmlTextReader((TextReader)stringReader); label_25: while (xmlTextReader.Read()) { if (flag) { str1 = stack.Count != 0 ? (string)stack.Pop() : ""; } if (xmlTextReader.NodeType == XmlNodeType.EndElement) { str1 = stack.Count != 0 ? (string)stack.Pop() : ""; } while (xmlTextReader.LineNumber > lineNumber1 && lineNumber1 <= end) { if (xmlNodeType == XmlNodeType.CDATA || xmlNodeType == XmlNodeType.Comment) { ++lineNumber1; } else { LineSegment lineSegment = document.GetLineSegment(lineNumber1); string text1 = document.GetText((ISegment)lineSegment); string text2 = !(text1.Trim() == ">") ? str1 + text1.Trim() : (string)stack.Peek() + text1.Trim(); if (text2 != text1) { document.Replace(lineSegment.Offset, lineSegment.Length, text2); ++x; } ++lineNumber1; } } if (xmlTextReader.LineNumber <= end) { flag = xmlTextReader.NodeType == XmlNodeType.Element && xmlTextReader.IsEmptyElement; string str2 = (string)null; if (xmlTextReader.NodeType == XmlNodeType.Element) { stack.Push((object)str1); if (xmlTextReader.LineNumber < begin) { str1 = this.GetIndentation(textArea, xmlTextReader.LineNumber - 1); } str2 = xmlTextReader.Name.Length >= 16 ? str1 + indentationString : str1 + new string(' ', 2 + xmlTextReader.Name.Length); str1 = str1 + indentationString; } xmlNodeType = xmlTextReader.NodeType; if (xmlTextReader.NodeType == XmlNodeType.Element && xmlTextReader.HasAttributes) { int lineNumber2 = xmlTextReader.LineNumber; xmlTextReader.MoveToAttribute(0); if (xmlTextReader.LineNumber != lineNumber2) { str2 = str1; } xmlTextReader.MoveToAttribute(xmlTextReader.AttributeCount - 1); while (true) { if (xmlTextReader.LineNumber > lineNumber1 && lineNumber1 <= end) { LineSegment lineSegment = document.GetLineSegment(lineNumber1); string text1 = document.GetText((ISegment)lineSegment); string text2 = str2 + text1.Trim(); if (text2 != text1) { document.Replace(lineSegment.Offset, lineSegment.Length, text2); ++x; } ++lineNumber1; } else { goto label_25; } } } } else { break; } } xmlTextReader.Close(); } catch (XmlException ex) { } finally { if (xmlTextReader != null) { xmlTextReader.Close(); } } } if (x <= 1) { return; } document.UndoStack.Undo(); }
public override bool Read() { if (_nodeType == XmlNodeType.Attribute && MoveToNextAttribute()) { return(true); } MoveNext(_element.dataNode); switch (_internalNodeType) { case ExtensionDataNodeType.Element: case ExtensionDataNodeType.ReferencedElement: case ExtensionDataNodeType.NullElement: PushElement(); SetElement(); break; case ExtensionDataNodeType.Text: _nodeType = XmlNodeType.Text; _prefix = string.Empty; _ns = string.Empty; _localName = string.Empty; _attributeCount = 0; _attributeIndex = -1; break; case ExtensionDataNodeType.EndElement: _nodeType = XmlNodeType.EndElement; _prefix = string.Empty; _ns = string.Empty; _localName = string.Empty; _value = string.Empty; _attributeCount = 0; _attributeIndex = -1; PopElement(); break; case ExtensionDataNodeType.None: if (_depth != 0) { throw new XmlException(SR.InvalidXmlDeserializingExtensionData); } _nodeType = XmlNodeType.None; _prefix = string.Empty; _ns = string.Empty; _localName = string.Empty; _value = string.Empty; _attributeCount = 0; _readState = ReadState.EndOfFile; return(false); case ExtensionDataNodeType.Xml: // do nothing break; default: Fx.Assert("ExtensionDataReader in invalid state"); throw new SerializationException(SR.InvalidStateInExtensionDataReader); } _readState = ReadState.Interactive; return(true); }
/// <summary> /// End reading by transitioning into the Closed state. /// </summary> public override void Close() { this.nav = XmlEmptyNavigator.Singleton; this.nodeType = XmlNodeType.None; this.state = State.Closed; this.depth = 0; }
private void ThrowUnexpectedStateException(XmlNodeType expectedState) { _ilg.Call(null, XmlFormatGeneratorStatics.CreateUnexpectedStateExceptionMethod, expectedState, _xmlReaderArg); _ilg.Throw(); }
private int TestOuterOnNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); DataReader.Read(); XmlNodeType expNt = DataReader.NodeType; string expName = DataReader.Name; string expValue = DataReader.Value; ReloadSource(); PositionOnNodeType(nt); CError.Compare(DataReader.ReadOuterXml(), String.Empty, "outer"); CError.Compare(DataReader.VerifyNode(expNt, expName, expValue), true, "vn"); return TEST_PASS; }
public List <Form> ParseDocument() { var reader = new XmlTextReader(_documentPath); Form formTag = null; string condition = null; while (reader.Read()) { XmlNodeType type = reader.NodeType; if (type == XmlNodeType.Element) { if (reader.Name == "form") { formTag = new Form(reader.GetAttribute("id")); _formList.Add(formTag); } if (reader.Name == "field") { formTag.Field = new Field(reader.GetAttribute("name")); } if (reader.Name == "block") { formTag.Block = new Block(); } if (reader.Name == "prompt") { if (formTag.Field != null && formTag.Field.Prompt == null) { formTag.Field.Prompt = new Prompt(reader.ReadString()); } if (formTag.Block != null && formTag.Block.Prompt == null) { var message = reader.ReadString(); formTag.Block.Prompt = new Prompt(message); } } if (reader.Name == "grammar") { formTag.Field.GrammarXmlFile = reader.GetAttribute("src"); } if (reader.Name == "nomatch") { if (formTag.Field != null && formTag.Field.NoMatch == null) { reader.ReadToDescendant("prompt"); formTag.Field.NoMatch = new Prompt(reader.ReadString()); } } if (reader.Name == "filled") { formTag.Field.Filled = new Filled(); } if (reader.Name == "if") { condition = reader.GetAttribute("cond").Split('\'', '\'')[1]; } if (reader.Name == "elseif") { condition = reader.GetAttribute("cond").Split('\'', '\'')[1]; } if (reader.Name == "goto") { formTag.Field.Filled.ConditionsDictionary.Add(condition, reader.GetAttribute("next").Trim(new char[] { '#' })); condition = "default"; } } } return(_formList); }
protected int FindNodeType(XmlNodeType nodeType) { return DataReader.FindNodeType(nodeType); }
/// <summary> /// Load the project settings for a specific transform file and return it /// </summary> /// <param name="sourceFile">The full path to the data file</param> /// <param name="baseDirectory">The path for the base directory (with a trailing \)</param> /// <param name="arguments">Argument list to pass to the returned transform</param> /// <param name="project">The context project</param> /// <param name="automationObjectName">The name of an automation object supported by the live document. Used /// to get a live version of the file stream.</param> /// <returns>The transform file name. Existence will have been verified.</returns> private string LoadProjectSettings(string sourceFile, string baseDirectory, XsltArgumentList arguments, EnvDTE.Project project, out string automationObjectName) { #if VerifyUIThread Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); #endif Debug.Assert(arguments != null); // Allocate before call string transformFile = null; automationObjectName = null; string plixProjectSettingsFile = baseDirectory + PlixProjectSettingsFile; if (File.Exists(plixProjectSettingsFile)) { // Use the text from the live document if possible string liveText = null; EnvDTE.Document settingsDoc = null; try { settingsDoc = project.DTE.Documents.Item(plixProjectSettingsFile); } catch (ArgumentException) { // swallow } catch (InvalidCastException) { // swallow } if (settingsDoc != null) { EnvDTE.TextDocument textDoc = settingsDoc.Object("TextDocument") as EnvDTE.TextDocument; if (textDoc != null) { liveText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint); } } string sourceFileIdentifier = sourceFile.Substring(baseDirectory.Length); PlixLoaderNameTable names = PlixLoaderSchema.Names; using (FileStream plixSettingsStream = (liveText == null) ? new FileStream(plixProjectSettingsFile, FileMode.Open, FileAccess.Read) : null) { using (XmlTextReader settingsReader = new XmlTextReader((liveText == null) ? new StreamReader(plixSettingsStream) as TextReader : new StringReader(liveText), names)) { using (XmlReader reader = XmlReader.Create(settingsReader, PlixLoaderSchema.ReaderSettings)) { References references = null; bool finished = false; while (!finished && reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (!reader.IsEmptyElement) { while (reader.Read()) { XmlNodeType nodeType = reader.NodeType; if (nodeType == XmlNodeType.Element) { Debug.Assert(XmlUtility.TestElementName(reader.LocalName, names.SourceFileElement)); // Only value allowed by the validating loader string testFileName = reader.GetAttribute(names.FileAttribute); if (0 == string.Compare(testFileName, sourceFileIdentifier, true, CultureInfo.CurrentCulture)) { finished = true; // Stop looking string attrValue = reader.GetAttribute(names.TransformFileAttribute); if (attrValue != null && attrValue.Length != 0) { transformFile = baseDirectory + attrValue; } attrValue = reader.GetAttribute(names.LiveDocumentObjectAttribute); if (attrValue != null && attrValue.Length != 0) { automationObjectName = attrValue; } if (!reader.IsEmptyElement) { while (reader.Read()) { nodeType = reader.NodeType; if (nodeType == XmlNodeType.Element) { string localName = reader.LocalName; if (XmlUtility.TestElementName(localName, names.TransformParameterElement)) { // Add an argument for the transform arguments.AddParam(reader.GetAttribute(names.NameAttribute), "", reader.GetAttribute(names.ValueAttribute)); } else if (XmlUtility.TestElementName(localName, names.ExtensionClassElement)) { // Load an extension class and associate it with an extension namespace // used by the transform arguments.AddExtensionObject(reader.GetAttribute(names.XslNamespaceAttribute), Type.GetType(reader.GetAttribute(names.ClassNameAttribute), true, false).GetConstructor(Type.EmptyTypes).Invoke(new object[0])); } else if (XmlUtility.TestElementName(localName, names.ProjectReferenceElement)) { // The generated code requires project references, add them if (null == references) { references = ((VSProject)project.Object).References; } if (references.Item(reader.GetAttribute(names.NamespaceAttribute)) == null) { references.Add(reader.GetAttribute(names.AssemblyAttribute)); } } else { Debug.Assert(false); // Not allowed by schema definition } XmlUtility.PassEndElement(reader); } else if (nodeType == XmlNodeType.EndElement) { break; } } } break; } XmlUtility.PassEndElement(reader); } else if (nodeType == XmlNodeType.EndElement) { break; } } } } } } } } } bool verifiedExistence = false; if (transformFile == null) { string fileBase = sourceFile.Substring(0, sourceFile.LastIndexOf('.')); transformFile = fileBase + ".xslt"; if (File.Exists(transformFile)) { verifiedExistence = true; } else { transformFile = fileBase + ".xsl"; } } if (!verifiedExistence && !File.Exists(transformFile)) { transformFile = null; } return(transformFile); }
/// <summary> /// End reading by transitioning into the Closed state. /// </summary> public override void Close() { _nav = XmlEmptyNavigator.Singleton; _nodeType = XmlNodeType.None; _state = State.Closed; _depth = 0; }
// Token: 0x0600099D RID: 2461 RVA: 0x0004418C File Offset: 0x0004238C internal void Load(string registryFile, string folder) { ExTraceGlobals.FormsRegistryCallTracer.TraceDebug <string, string>((long)this.GetHashCode(), "FormsRegistryParser.Load registry file = {0}, folder = {1}", registryFile, folder); this.registryFile = registryFile; bool flag = false; string name = string.Empty; string inheritsFrom = string.Empty; string baseExperience = string.Empty; bool isRichClient = false; try { this.reader = SafeXmlFactory.CreateSafeXmlTextReader(registryFile); this.reader.WhitespaceHandling = WhitespaceHandling.None; this.registry = new FormsRegistry(); this.reader.Read(); if (this.reader.Name != FormsRegistryParser.nameTableValues[0]) { this.ThrowExpectedElementException(FormsRegistryParser.NameTableValues.Registry); } if (!this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[1])) { this.ThrowExpectedAttributeException(FormsRegistryParser.NameTableValues.Name); } name = this.reader.Value; if (this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[3])) { inheritsFrom = this.reader.Value; if (this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[2])) { this.ThrowParserException("BaseExperience is not valid when inheriting from another registry. The BaseExperience from the inherited registry is used instead", ClientsEventLogConstants.Tuple_FormsRegistryInvalidUserOfBaseExperience, new object[] { registryFile, this.reader.LineNumber.ToString(CultureInfo.InvariantCulture), this.reader.LinePosition.ToString(CultureInfo.InvariantCulture) }); } } else if (this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[2])) { baseExperience = this.reader.Value; } else { this.ThrowParserException("Expected BaseExperience or InheritsFrom attribute", ClientsEventLogConstants.Tuple_FormsRegistryExpectedBaseExperienceOrInheritsFrom, new object[] { registryFile, this.reader.LineNumber.ToString(CultureInfo.InvariantCulture), this.reader.LinePosition.ToString(CultureInfo.InvariantCulture) }); } if (!this.reader.MoveToAttribute(FormsRegistryParser.nameTableValues[4])) { this.ThrowExpectedAttributeException(FormsRegistryParser.NameTableValues.IsRichClient); } try { isRichClient = bool.Parse(this.reader.Value); } catch (FormatException) { this.ThrowParserException("Expected a valid boolean value in IsRichClient property", ClientsEventLogConstants.Tuple_FormsRegistryInvalidUserOfIsRichClient, new object[] { registryFile, this.reader.LineNumber.ToString(CultureInfo.InvariantCulture), this.reader.LinePosition.ToString(CultureInfo.InvariantCulture), this.reader.Value }); } try { this.registry.Initialize(name, baseExperience, inheritsFrom, folder, isRichClient); goto IL_33E; } catch (OwaInvalidInputException ex) { OwaDiagnostics.LogEvent(ClientsEventLogConstants.Tuple_FormsRegistryParseError, ex.Message, new object[] { registryFile, this.reader.LineNumber.ToString(CultureInfo.InvariantCulture), this.reader.LinePosition.ToString(CultureInfo.InvariantCulture), ex.Message }); throw ex; } IL_2D4: XmlNodeType nodeType = this.reader.NodeType; if (nodeType != XmlNodeType.Element) { if (nodeType == XmlNodeType.EndElement) { if (this.reader.Name == FormsRegistryParser.nameTableValues[0]) { flag = true; } } } else if (this.reader.Name == FormsRegistryParser.nameTableValues[5]) { this.clientMappings.AddRange(this.ParseExperience()); } else { this.ThrowExpectedElementException(FormsRegistryParser.NameTableValues.Experience); } IL_33E: if (!flag && this.reader.Read()) { goto IL_2D4; } } catch (XmlException ex2) { this.ThrowParserException(ex2.Message, ClientsEventLogConstants.Tuple_FormsRegistryParseError, new object[] { registryFile, this.reader.LineNumber.ToString(CultureInfo.InvariantCulture), this.reader.LinePosition.ToString(CultureInfo.InvariantCulture), ex2.Message }); } finally { if (this.reader != null) { this.reader.Close(); } } }
protected XPathNavigatorReader(XPathNavigator navToRead, IXmlLineInfo xli, IXmlSchemaInfo xsi) { // Need clone that can be moved independently of original navigator _navToRead = navToRead; this.lineInfo = xli; this.schemaInfo = xsi; _nav = XmlEmptyNavigator.Singleton; _state = State.Initial; _depth = 0; _nodeType = XPathNavigatorReader.ToXmlNodeType(_nav.NodeType); }
public override bool MoveToNextAttribute() { switch (_state) { case State.Content: return MoveToFirstAttribute(); case State.Attribute: { if (XPathNodeType.Attribute == _nav.NodeType) return _nav.MoveToNextAttribute(); // otherwise it is on a namespace... namespace are in reverse order Debug.Assert(XPathNodeType.Namespace == _nav.NodeType); XPathNavigator nav = _nav.Clone(); if (!nav.MoveToParent()) return false; // shouldn't happen if (!nav.MoveToFirstNamespace(XPathNamespaceScope.Local)) return false; // shouldn't happen if (nav.IsSamePosition(_nav)) { // this was the last one... start walking attributes nav.MoveToParent(); if (!nav.MoveToFirstAttribute()) return false; // otherwise we are there _nav.MoveTo(nav); return true; } else { XPathNavigator prev = nav.Clone(); for (; ;) { if (!nav.MoveToNextNamespace(XPathNamespaceScope.Local)) { Debug.Fail("Couldn't find Namespace Node! Should not happen!"); return false; } if (nav.IsSamePosition(_nav)) { _nav.MoveTo(prev); return true; } prev.MoveTo(nav); } // found previous namespace position } } case State.AttrVal: _depth--; _state = State.Attribute; if (!MoveToNextAttribute()) { _depth++; _state = State.AttrVal; return false; } _nodeType = XmlNodeType.Attribute; return true; case State.InReadBinary: _state = _savedState; if (!MoveToNextAttribute()) { _state = State.InReadBinary; return false; } _readBinaryHelper.Finish(); return true; default: return false; } }
public override bool ReadAttributeValue() { if (_state == State.InReadBinary) { _readBinaryHelper.Finish(); _state = _savedState; } if (_state == State.Attribute) { _state = State.AttrVal; _nodeType = XmlNodeType.Text; _depth++; return true; } return false; }
protected void ReadReferencedElements() { reader.MoveToContent(); XmlNodeType nt = reader.NodeType; while (nt != XmlNodeType.EndElement && nt != XmlNodeType.None) { whileIterationCount++; readCount++; ReadReferencedElement(); reader.MoveToContent(); nt = reader.NodeType; } whileIterationCount = 0; // Registers delayed list if (delayedListFixups != null) { foreach (DictionaryEntry entry in delayedListFixups) { AddTarget((string)entry.Key, entry.Value); } } // Fix arrays if (collItemFixups != null) { foreach (CollectionItemFixup itemFixup in collItemFixups) { itemFixup.Collection.SetValue(GetTarget(itemFixup.Id), itemFixup.Index); } } // Fills collections if (collFixups != null) { ICollection cfixups = collFixups.Values; foreach (CollectionFixup fixup in cfixups) { fixup.Callback(fixup.Collection, fixup.CollectionItems); } } // Fills class instances if (fixups != null) { foreach (Fixup fixup in fixups) { fixup.Callback(fixup); } } if (targets != null) { foreach (DictionaryEntry e in targets) { if (e.Value != null && (referencedObjects == null || !referencedObjects.Contains(e.Value))) { UnreferencedObject((string)e.Key, e.Value); } } } }
public static void ReadUntilTypeReached(XmlReader reader, XmlNodeType nodeType) { ReadUntilAnyTypesReached(reader, new XmlNodeType[] { nodeType }); }
public void Dispose() { if (this.SetSamplerState(0, SamplerStatedomNode.SetSamplerState(0, SamplerStateParentNode.SetSamplerState(0, SamplerStateNodeType == XmlNodeType.SetSamplerState(0, SamplerStateDocumentFragment ) this.SetSamplerState(0, SamplerStatedomNode.SetSamplerState(0, SamplerStateParentNode.SetSamplerState(0, SamplerStateRemoveChild(this.SetSamplerState(0, SamplerStatedomNode ); }
public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId) { bool flag; errorDetails = null; httpStatusCode = 0; operationId = null; if (exception != null) { if (exception.Message != "Internal Server Error") { WebException innerException = exception.InnerException as WebException; if (innerException != null) { HttpWebResponse response = innerException.Response as HttpWebResponse; if (response != null) { if (response.Headers != null) { operationId = response.Headers["x-ms-request-id"]; } if (response.StatusCode != HttpStatusCode.NotFound) { Stream responseStream = response.GetResponseStream(); using (responseStream) { if (responseStream.Length != (long)0) { try { errorDetails = new ServiceManagementError(); responseStream.Seek((long)0, SeekOrigin.Begin); StreamReader streamReader = new StreamReader(responseStream); using (StringReader stringReader = new StringReader(streamReader.ReadToEnd())) { XmlReader xmlReader = XmlReader.Create(stringReader); while (xmlReader.Read()) { XmlNodeType nodeType = xmlReader.NodeType; if (nodeType != XmlNodeType.Element) { continue; } if (xmlReader.Name != "Code") { if (xmlReader.Name != "Message") { continue; } xmlReader.Read(); errorDetails.Message = xmlReader.Value; } else { xmlReader.Read(); errorDetails.Code = xmlReader.Value; } } } } catch (SerializationException serializationException) { flag = false; return(flag); } return(true); } else { flag = false; } } return(flag); } else { errorDetails = new ServiceManagementError(); errorDetails.Message = string.Concat(response.ResponseUri.AbsoluteUri, " does not exist."); errorDetails.Code = response.StatusCode.ToString(); return(false); } } else { return(false); } } else { return(false); } } else { httpStatusCode = HttpStatusCode.InternalServerError; return(true); } } else { return(false); } }
/// <summary> /// set reader to EOF state /// </summary> private void SetEOF() { this.nav = XmlEmptyNavigator.Singleton; this.nodeType = XmlNodeType.None; this.state = State.EOF; this.depth = 0; }
/// <summary> /// Format an Xml element to be written to the config file. /// </summary> /// <param name="xmlElement">the element</param> /// <param name="linePosition">start position of the element</param> /// <param name="indent">indent for each depth</param> /// <param name="skipFirstIndent">skip indent for the first element?</param> /// <returns></returns> internal static string FormatXmlElement(string xmlElement, int linePosition, int indent, bool skipFirstIndent) { XmlParserContext context = new XmlParserContext(null, null, null, XmlSpace.Default, Encoding.Unicode); XmlTextReader reader = new XmlTextReader(xmlElement, XmlNodeType.Element, context); StringWriter stringWriter = new StringWriter(new StringBuilder(64), CultureInfo.InvariantCulture); XmlUtilWriter utilWriter = new XmlUtilWriter(stringWriter, false); // append newline before indent? bool newLine = false; // last node visited was text? bool lastWasText = false; // length of the stringbuilder after last indent with newline int sbLengthLastNewLine = 0; while (reader.Read()) { XmlNodeType nodeType = reader.NodeType; int lineWidth; if (lastWasText) { utilWriter.Flush(); lineWidth = sbLengthLastNewLine - ((StringWriter)utilWriter.Writer).GetStringBuilder().Length; } else { lineWidth = 0; } switch (nodeType) { case XmlNodeType.CDATA: case XmlNodeType.Element: case XmlNodeType.EndElement: case XmlNodeType.Comment: // Do not indent if the last node was text - doing so would add whitespace // that is included as part of the text. if (!skipFirstIndent && !lastWasText) { utilWriter.AppendIndent(linePosition, indent, reader.Depth, newLine); if (newLine) { utilWriter.Flush(); sbLengthLastNewLine = ((StringWriter)utilWriter.Writer).GetStringBuilder().Length; } } break; } lastWasText = false; switch (nodeType) { case XmlNodeType.Whitespace: break; case XmlNodeType.SignificantWhitespace: utilWriter.Write(reader.Value); break; case XmlNodeType.CDATA: utilWriter.AppendCData(reader.Value); break; case XmlNodeType.ProcessingInstruction: utilWriter.AppendProcessingInstruction(reader.Name, reader.Value); break; case XmlNodeType.Comment: utilWriter.AppendComment(reader.Value); break; case XmlNodeType.Text: utilWriter.AppendEscapeTextString(reader.Value); lastWasText = true; break; case XmlNodeType.Element: { // Write "<elem" utilWriter.Write('<'); utilWriter.Write(reader.Name); lineWidth += reader.Name.Length + 2; int c = reader.AttributeCount; for (int i = 0; i < c; i++) { // Add new line if we've exceeded the line width bool writeSpace; if (lineWidth > MaxLineWidth) { utilWriter.AppendIndent(linePosition, indent, reader.Depth - 1, true); lineWidth = indent; writeSpace = false; utilWriter.Flush(); sbLengthLastNewLine = ((StringWriter)utilWriter.Writer).GetStringBuilder().Length; } else { writeSpace = true; } // Write the attribute reader.MoveToNextAttribute(); utilWriter.Flush(); int startLength = ((StringWriter)utilWriter.Writer).GetStringBuilder().Length; if (writeSpace) { utilWriter.AppendSpace(); } utilWriter.Write(reader.Name); utilWriter.Write('='); utilWriter.AppendAttributeValue(reader); utilWriter.Flush(); lineWidth += ((StringWriter)utilWriter.Writer).GetStringBuilder().Length - startLength; } } // position reader back on element reader.MoveToElement(); // write closing tag if (reader.IsEmptyElement) { utilWriter.Write(" />"); } else { utilWriter.Write('>'); } break; case XmlNodeType.EndElement: utilWriter.Write("</"); utilWriter.Write(reader.Name); utilWriter.Write('>'); break; case XmlNodeType.EntityReference: utilWriter.AppendEntityRef(reader.Name); break; // Ignore <?xml and <!DOCTYPE nodes // case XmlNodeType.XmlDeclaration: // case XmlNodeType.DocumentType: } // put each new element on a new line newLine = true; // do not skip any more indents skipFirstIndent = false; } utilWriter.Flush(); string s = ((StringWriter)utilWriter.Writer).ToString(); return(s); }
////////////////////////////////////////// // PositionOnNodeType ////////////////////////////////////////// protected void PositionOnNodeType(XmlNodeType nodeType) { DataReader.PositionOnNodeType(nodeType); }
private static int GetPositionOffset(XmlNodeType nodeType) { return(s_positionOffset[(int)nodeType]); }
public bool VerifySkipOnNodeType(XmlNodeType testNodeType) { bool bPassed = false; XmlNodeType actNodeType; String strActName; String strActValue; ReloadSource(); PositionOnNodeType(testNodeType); DataReader.Read(); actNodeType = DataReader.NodeType; strActName = DataReader.Name; strActValue = DataReader.Value; ReloadSource(); PositionOnNodeType(testNodeType); DataReader.Skip(); bPassed = DataReader.VerifyNode(actNodeType, strActName, strActValue); return bPassed; }
// Copy a single XML node, attempting to preserve whitespace. // A side effect of this method is to advance the reader to the next node. // // PERFORMANCE NOTE: this function is used at runtime to copy a configuration section, // and at designtime to copy an entire XML document. // // At designtime, this function needs to be able to copy a <!DOCTYPE declaration. // Copying a <!DOCTYPE declaration is expensive, because due to limitations of the // XmlReader API, we must track the position of the writer to accurately format it. // Tracking the position of the writer is expensive, as it requires examining every // character that is written for newline characters, and maintaining the seek position // of the underlying stream at each new line, which in turn requires a stream flush. // // This function must NEVER require tracking the writer position to copy the Xml nodes // that are used in a configuration section. internal bool CopyXmlNode(XmlUtilWriter utilWriter) { // For nodes that have a closing string, such as "<element >" // the XmlReader API does not give us the location of the closing string, e.g. ">". // To correctly determine the location of the closing part, we advance the reader, // determine the position of the next node, then work backwards to add whitespace // and add the closing string. string close = null; int lineNumber = -1; int linePosition = -1; int readerLineNumber = 0; int readerLinePosition = 0; int writerLineNumber = 0; int writerLinePosition = 0; if (utilWriter.TrackPosition) { readerLineNumber = Reader.LineNumber; readerLinePosition = Reader.LinePosition; writerLineNumber = utilWriter.LineNumber; writerLinePosition = utilWriter.LinePosition; } // We test the node type in the likely order of decreasing occurrence. XmlNodeType nodeType = Reader.NodeType; if (nodeType == XmlNodeType.Whitespace) { utilWriter.Write(Reader.Value); } else { if (nodeType == XmlNodeType.Element) { close = Reader.IsEmptyElement ? "/>" : ">"; // get the line position after the element declaration: // <element attr="value" // ^ // linePosition lineNumber = Reader.LineNumber; linePosition = Reader.LinePosition + Reader.Name.Length; utilWriter.Write('<'); utilWriter.Write(Reader.Name); // Note that there is no way to get spacing between attribute name and value // For example: // // <elem attr="value" /> // // is reported with the same position as // // <elem attr = "value" /> // // The first example has no spaces around '=', the second example does. while (Reader.MoveToNextAttribute()) { // get line position of the attribute declaration // <element attr="value" // ^ // attrLinePosition int attrLineNumber = Reader.LineNumber; int attrLinePosition = Reader.LinePosition; // Write the whitespace before the attribute utilWriter.AppendRequiredWhiteSpace(lineNumber, linePosition, attrLineNumber, attrLinePosition); // Write the attribute and value int charactersWritten = utilWriter.Write(Reader.Name); charactersWritten += utilWriter.Write('='); charactersWritten += utilWriter.AppendAttributeValue(Reader); // Update position. Note that the attribute value is escaped to always be on a single line. lineNumber = attrLineNumber; linePosition = attrLinePosition + charactersWritten; } } else { if (nodeType == XmlNodeType.EndElement) { close = ">"; // get line position after the end element declaration: // </element > // ^ // linePosition lineNumber = Reader.LineNumber; linePosition = Reader.LinePosition + Reader.Name.Length; utilWriter.Write("</"); utilWriter.Write(Reader.Name); } else { if (nodeType == XmlNodeType.Comment) { utilWriter.AppendComment(Reader.Value); } else { if (nodeType == XmlNodeType.Text) { utilWriter.AppendEscapeTextString(Reader.Value); } else { if (nodeType == XmlNodeType.XmlDeclaration) { close = "?>"; // get line position after the xml declaration: // <?xml version="1.0" // ^ // linePosition lineNumber = Reader.LineNumber; linePosition = Reader.LinePosition + 3; utilWriter.Write("<?xml"); // Note that there is no way to get spacing between attribute name and value // For example: // // <?xml attr="value" ?> // // is reported with the same position as // // <?xml attr = "value" ?> // // The first example has no spaces around '=', the second example does. while (Reader.MoveToNextAttribute()) { // get line position of the attribute declaration // <?xml version="1.0" // ^ // attrLinePosition int attrLineNumber = Reader.LineNumber; int attrLinePosition = Reader.LinePosition; // Write the whitespace before the attribute utilWriter.AppendRequiredWhiteSpace(lineNumber, linePosition, attrLineNumber, attrLinePosition); // Write the attribute and value int charactersWritten = utilWriter.Write(Reader.Name); charactersWritten += utilWriter.Write('='); charactersWritten += utilWriter.AppendAttributeValue(Reader); // Update position. Note that the attribute value is escaped to always be on a single line. lineNumber = attrLineNumber; linePosition = attrLinePosition + charactersWritten; } // Position reader at beginning of node Reader.MoveToElement(); } else { if (nodeType == XmlNodeType.SignificantWhitespace) { utilWriter.Write(Reader.Value); } else { if (nodeType == XmlNodeType.ProcessingInstruction) { // Note that there is no way to get spacing between attribute name and value // For example: // // <?pi "value" ?> // // is reported with the same position as // // <?pi "value" ?> // // The first example has one space between 'pi' and "value", the second has multiple spaces. utilWriter.AppendProcessingInstruction(Reader.Name, Reader.Value); } else { if (nodeType == XmlNodeType.EntityReference) { utilWriter.AppendEntityRef(Reader.Name); } else { if (nodeType == XmlNodeType.CDATA) { utilWriter.AppendCData(Reader.Value); } else { if (nodeType == XmlNodeType.DocumentType) { // XmlNodeType.DocumentType has the following format: // // <!DOCTYPE rootElementName {(SYSTEM uriRef)|(PUBLIC id uriRef)} {[ dtdDecls ]} > // // The reader only gives us the position of 'rootElementName', so we must track what was // written before "<!DOCTYPE" in order to correctly determine the position of the // <!DOCTYPE tag Debug.Assert(utilWriter.TrackPosition, "utilWriter.TrackPosition"); int c = utilWriter.Write("<!DOCTYPE"); // Write the space between <!DOCTYPE and the rootElementName utilWriter.AppendRequiredWhiteSpace(_lastLineNumber, _lastLinePosition + c, Reader.LineNumber, Reader.LinePosition); // Write the rootElementName utilWriter.Write(Reader.Name); // Get the dtd declarations, if any string dtdValue = null; if (Reader.HasValue) { dtdValue = Reader.Value; } // get line position after the !DOCTYPE declaration: // <!DOCTYPE rootElement SYSTEM rootElementDtdUri > // ^ // linePosition lineNumber = Reader.LineNumber; linePosition = Reader.LinePosition + Reader.Name.Length; // Note that there is no way to get the spacing after PUBLIC or SYSTEM attributes and their values if (Reader.MoveToFirstAttribute()) { // Write the space before SYSTEM or PUBLIC utilWriter.AppendRequiredWhiteSpace(lineNumber, linePosition, Reader.LineNumber, Reader.LinePosition); // Write SYSTEM or PUBLIC and the 1st value of the attribute string attrName = Reader.Name; utilWriter.Write(attrName); utilWriter.AppendSpace(); utilWriter.AppendAttributeValue(Reader); Reader.MoveToAttribute(0); // If PUBLIC, write the second value of the attribute if (attrName == "PUBLIC") { Reader.MoveToAttribute(1); utilWriter.AppendSpace(); utilWriter.AppendAttributeValue(Reader); Reader.MoveToAttribute(1); } } // If there is a dtd, write it if (!string.IsNullOrEmpty(dtdValue)) { utilWriter.Write(" ["); utilWriter.Write(dtdValue); utilWriter.Write(']'); } utilWriter.Write('>'); } } } } } } } } } } } // Advance the _reader so we can get the position of the next node. bool moreToRead = Reader.Read(); nodeType = Reader.NodeType; // Close the node we are copying. if (close != null) { // Find the position of the close string, for example: // <element > <subElement /> // ^ // closeLinePosition int startOffset = GetPositionOffset(nodeType); int closeLineNumber = Reader.LineNumber; int closeLinePosition = Reader.LinePosition - startOffset - close.Length; // Add whitespace up to the position of the close string utilWriter.AppendWhiteSpace(lineNumber, linePosition, closeLineNumber, closeLinePosition); // Write the close string utilWriter.Write(close); } // Track the position of the reader based on the position of the reader // before we copied this node and what we have written in copying the node. // This allows us to determine the position of the <!DOCTYPE tag. if (utilWriter.TrackPosition) { _lastLineNumber = readerLineNumber - writerLineNumber + utilWriter.LineNumber; if (writerLineNumber == utilWriter.LineNumber) { _lastLinePosition = readerLinePosition - writerLinePosition + utilWriter.LinePosition; } else { _lastLinePosition = utilWriter.LinePosition; } } return(moreToRead); }
/// <summary> /// set reader to EOF state /// </summary> private void SetEOF() { _nav = XmlEmptyNavigator.Singleton; _nodeType = XmlNodeType.None; _state = State.EOF; _depth = 0; }
// // Constructors // public CXmlNode(string strPrefix, string strName, XmlNodeType NodeType) : base(strPrefix, strName, NodeType) { }
private void MoveToAttr(XPathNavigator nav, int depth) { _nav.MoveTo(nav); _depth = depth; _nodeType = XmlNodeType.Attribute; _state = State.Attribute; }
public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType, string strNamespace) : this(strPrefix, strName, strName, NodeType, strNamespace) { }
public override bool MoveToElement() { switch (_state) { case State.Attribute: case State.AttrVal: if (!_nav.MoveToParent()) return false; _depth--; if (_state == State.AttrVal) _depth--; _state = State.Content; _nodeType = XmlNodeType.Element; return true; case State.InReadBinary: _state = _savedState; if (!MoveToElement()) { _state = State.InReadBinary; return false; } _readBinaryHelper.Finish(); break; } return false; }
public CXmlBase(string strName, XmlNodeType NodeType) : this("", strName, strName, NodeType, "") { }
/// <summary> /// Move to the next reader state. Return false if that is ReaderState.Closed. /// </summary> public override bool Read() { _attrCount = -1; switch (_state) { case State.Error: case State.Closed: case State.EOF: return false; case State.Initial: // Starting state depends on the navigator's item type _nav = _navToRead; _state = State.Content; if (XPathNodeType.Root == _nav.NodeType) { if (!_nav.MoveToFirstChild()) { SetEOF(); return false; } _readEntireDocument = true; } else if (XPathNodeType.Attribute == _nav.NodeType) { _state = State.Attribute; } _nodeType = ToXmlNodeType(_nav.NodeType); break; case State.Content: if (_nav.MoveToFirstChild()) { _nodeType = ToXmlNodeType(_nav.NodeType); _depth++; _state = State.Content; } else if (_nodeType == XmlNodeType.Element && !_nav.IsEmptyElement) { _nodeType = XmlNodeType.EndElement; _state = State.EndElement; } else goto case State.EndElement; break; case State.EndElement: if (0 == _depth && !_readEntireDocument) { SetEOF(); return false; } else if (_nav.MoveToNext()) { _nodeType = ToXmlNodeType(_nav.NodeType); _state = State.Content; } else if (_depth > 0 && _nav.MoveToParent()) { Debug.Assert(_nav.NodeType == XPathNodeType.Element, _nav.NodeType.ToString() + " == XPathNodeType.Element"); _nodeType = XmlNodeType.EndElement; _state = State.EndElement; _depth--; } else { SetEOF(); return false; } break; case State.Attribute: case State.AttrVal: if (!_nav.MoveToParent()) { SetEOF(); return false; } _nodeType = ToXmlNodeType(_nav.NodeType); _depth--; if (_state == State.AttrVal) _depth--; goto case State.Content; case State.InReadBinary: _state = _savedState; _readBinaryHelper.Finish(); return Read(); } return true; }
GetImageIndex(XmlNodeType nType) { int imageIndex = 0; // associate the correct image with this type of node if (nType == XmlNodeType.Document) { imageIndex = 0; } else if (nType == XmlNodeType.Attribute) { imageIndex = 1; } else if (nType == XmlNodeType.CDATA) { imageIndex = 2; } else if (nType == XmlNodeType.Comment) { imageIndex = 3; } else if (nType == XmlNodeType.DocumentType) { imageIndex = 4; } else if (nType == XmlNodeType.Element) { imageIndex = 5; } else if (nType == XmlNodeType.Entity) { imageIndex = 6; } else if (nType == XmlNodeType.DocumentFragment) { imageIndex = 7; } else if (nType == XmlNodeType.ProcessingInstruction) { imageIndex = 8; } else if (nType == XmlNodeType.EntityReference) { imageIndex = 9; } else if (nType == XmlNodeType.Text) { imageIndex = 10; } else if (nType == XmlNodeType.XmlDeclaration) { imageIndex = 11; } // TBD: Not sure what when the rest of these come up yet? // I will reserve a spot in case they become significant else if (nType == XmlNodeType.EndElement) { imageIndex = 12; } else if (nType == XmlNodeType.EndEntity) { imageIndex = 12; } else if (nType == XmlNodeType.None) { imageIndex = 12; } else if (nType == XmlNodeType.Notation) { imageIndex = 12; } else if (nType == XmlNodeType.SignificantWhitespace) { imageIndex = 12; } else if (nType == XmlNodeType.Whitespace) { imageIndex = 12; } else { Debug.Assert(false); imageIndex = 12; } return(imageIndex); }