static void Main(string[] args) { StringWriter w = new StringWriter(); w.WriteLine("Sing a song of {0} pence", 6); string s = "A pocket full of rye"; w.Write(s); w.Write(w.NewLine); w.Write(string.Format(4 + " and " + 20 + " blackbirds")); w.Write(new StringBuilder(" baked in a pie")); w.WriteLine(); Console.WriteLine(w); StringBuilder sb = w.GetStringBuilder(); int i = sb.Length; sb.Append("The birds began to sing"); sb.Insert(i, "when the pie was opened\n"); sb.AppendFormat("\nWasn't that a {0} to set before the king", "dainty dish"); Console.WriteLine(w); Console.WriteLine(); StringReader r = new StringReader(w.ToString()); string t = r.ReadLine(); Console.WriteLine(t); Console.Write((char)r.Read()); char[] ca = new char[37]; r.Read(ca, 0, 19); Console.Write(ca); Console.WriteLine(r.ReadToEnd()); r.Close(); w.Close(); Console.ReadLine(); }
/// <summary> /// UrlDecodes a string without requiring System.Web /// </summary> /// <param name="InputString">String to decode.</param> /// <returns>decoded string</returns> public static string UrlDecode(string InputString) { char temp = ' '; StringReader sr = new StringReader(InputString); StringBuilder sb = new StringBuilder( InputString.Length ); while (true) { int lnVal = sr.Read(); if (lnVal == -1) break; char TChar = (char) lnVal; if (TChar == '+') sb.Append(' '); else if(TChar == '%') { // *** read the next 2 chars and parse into a char temp = (char) Int32.Parse(((char) sr.Read()).ToString() + ((char) sr.Read()).ToString(), System.Globalization.NumberStyles.HexNumber); sb.Append(temp); } else sb.Append(TChar); } return sb.ToString(); }
public string Parse(string message) { StringBuilder sb = new StringBuilder(); StringReader sr = new StringReader(message); char[] buf = new char[1]; while (sr.Read(buf, 0, 1) > 0) { if (buf[0] == '&') { if (sr.Read(buf, 0, 1) > 0) { if (buf[0] == '&') sb.Append('&'); else sb.Append(GetColor(buf[0])); } else break; } else { sb.Append(buf[0]); } } return sb.ToString(); }
public void AddExpression(string name, string regex) { using (var stream = new StringReader(InfixToPostfix.Convert(regex))) { while (stream.Peek() != -1) { var c = (char) stream.Read(); switch (c) { case '.': _stack.Concatenate(); break; case '|': _stack.Unite(); break; case '*': _stack.Iterate(); break; case '+': _stack.AtLeast(); break; case '?': _stack.Maybe(); break; default: var a = new NFA<char>(); a.AddTransition(a.Start, new State(), c == '\\' ? Escape((char) stream.Read()) : c); _stack.Push(a); break; } } var top = _stack.Peek(); top.LastAdded.Final = true; top.SetName(top.LastAdded, name); } }
/* The Method Factor checks if the next Element in the String is an Element of the Lists * varibles or digit or read.peek() is -1 (then theres no next element in the string) if not it has to be a "(" otherwise the expression is false */ private void Factor(StringReader reader) { if (variables.Contains((char)reader.Peek())) { reader.Read(); return; } else if (digit.Contains((char)reader.Peek())) { reader.Read(); Constant(reader); return; } else if ((char)reader.Peek() == '(') { reader.Read(); Expression(reader); if ((char)reader.Peek() == ')') { reader.Read(); return; } else { throw new ParseError("\")\" expected"); } } else if (reader.Peek() == -1) // wenn der reader -1 als nächstes zeichen sieht dann ist string zu ende gelesen { return; } else throw new ParseError("invalid factor in "+ expressionString); }
public string format(string text) { reader = new StringReader(text); int cache; while((cache = reader.Peek()) != -1) { if(cache == '%') { reader.Read(); string c; if((c = controlIdentify()) != null) { builder.Append(c); }else { break; } } else { builder.Append((char)reader.Read()); } } return builder.ToString(); }
public static string RemoveSpaces2(string value, int length) { var stringBuilder = new StringBuilder(); using (var stringReader = new StringReader(value)) { while (stringReader.Peek() != -1) { var ch = (char)stringReader.Peek(); if (char.IsWhiteSpace(ch)) { while (char.IsWhiteSpace(ch)) { stringReader.Read(); ch = (char)stringReader.Peek(); } if (stringBuilder.Length != 0 && stringBuilder.Length < length) { stringBuilder.Append("%20"); } } else { stringBuilder.Append((char)stringReader.Read()); } } } return stringBuilder.ToString(); }
public IEnumerable<Token> Scan(string expression) { _reader = new StringReader(expression); var tokens = new List<Token>(); while (_reader.Peek() != -1) { var c = (char)_reader.Peek(); if (Char.IsWhiteSpace(c)) { _reader.Read(); continue; } if (Char.IsDigit(c)) { var nr = ParseNumber(); tokens.Add(new NumberConstantToken(nr)); } else if (c == '-') { tokens.Add(new MinusToken()); _reader.Read(); } else if (c == '+') { tokens.Add(new PlusToken()); _reader.Read(); } else throw new Exception("Unknown character in expression: " + c); } return tokens; }
/// <summary> /// Converts a string to a number (used by parseFloat). /// </summary> /// <param name="input"> The string to convert. </param> /// <returns> The result of parsing the string as a number. </returns> internal static double ParseFloat(string input) { var reader = new System.IO.StringReader(input); // Skip whitespace and line terminators. while (IsWhiteSpaceOrLineTerminator(reader.Peek())) { reader.Read(); } // The number can start with a plus or minus sign. bool negative = false; int firstChar = reader.Read(); switch (firstChar) { case '-': negative = true; firstChar = reader.Read(); break; case '+': firstChar = reader.Read(); break; } // Infinity or -Infinity are also valid. if (firstChar == 'I') { var nfinityString = reader.ReadToEnd(); if (nfinityString == null) { throw new InvalidOperationException("Reader returned null."); } if (nfinityString.StartsWith("nfinity", StringComparison.Ordinal)) { return(negative ? double.NegativeInfinity : double.PositiveInfinity); } } // Empty strings return NaN. if ((firstChar < '0' || firstChar > '9') && firstChar != '.') { return(double.NaN); } // Parse the number. NumberParser.ParseCoreStatus status; var result = NumberParser.ParseCore(reader, (char)firstChar, out status, false, false); // Handle various error cases. if (status == ParseCoreStatus.NoDigits) { return(double.NaN); } return(negative ? -result : result); }
// The parsing logic is based on http://www.w3.org/TR/CSS2/syndata.html. internal static string TransformCssFile( string sourceCssText ) { sourceCssText = RegularExpressions.RemoveMultiLineCStyleComments( sourceCssText ); var customElementsDetected = from Match match in Regex.Matches( sourceCssText, customElementPattern ) select match.Value; customElementsDetected = customElementsDetected.Distinct(); var knownCustomElements = CssPreprocessingStatics.Elements.Select( ce => reservedCustomElementPrefix + ce.Name ); var unknownCustomElements = customElementsDetected.Except( knownCustomElements ).ToList(); if( unknownCustomElements.Any() ) { throw new MultiMessageApplicationException( unknownCustomElements.Select( e => "\"" + e + "\" begins with the reserved custom element prefix but is not a known custom element." ).ToArray() ); } using( var writer = new StringWriter() ) { var buffer = new StringBuilder(); using( var reader = new StringReader( sourceCssText ) ) { char? stringDelimiter = null; while( reader.Peek() != -1 ) { var c = (char)reader.Read(); // escaped quote, brace, or other character if( c == '\\' ) { buffer.Append( c ); if( reader.Peek() != -1 ) buffer.Append( (char)reader.Read() ); } // string delimiter else if( !stringDelimiter.HasValue && ( c == '\'' || c == '"' ) ) { buffer.Append( c ); stringDelimiter = c; } else if( stringDelimiter.HasValue && c == stringDelimiter ) { buffer.Append( c ); stringDelimiter = null; } // selector delimiter else if( !stringDelimiter.HasValue && ( c == ',' || c == '{' ) ) { writer.Write( getTransformedSelector( buffer.ToString() ) ); writer.Write( c ); buffer = new StringBuilder(); } else if( !stringDelimiter.HasValue && c == '}' ) { writer.Write( buffer.ToString() ); writer.Write( c ); buffer = new StringBuilder(); } // other character else buffer.Append( c ); } } writer.Write( buffer.ToString() ); return writer.ToString(); } }
/// <summary> /// Gets a string representation of a code element using the specified /// format. /// </summary> /// <param name="format">The format.</param> /// <param name="codeElement">The code element.</param> /// <returns>Formatted string representation of the code element.</returns> public static string Format(string format, ICodeElement codeElement) { if (format == null) { throw new ArgumentNullException("format"); } else if (codeElement == null) { throw new ArgumentNullException("codeElement"); } StringBuilder formatted = new StringBuilder(format.Length*2); StringBuilder attributeBuilder = null; bool inAttribute = false; using (StringReader reader = new StringReader(format)) { int data = reader.Read(); while (data > 0) { char ch = (char) data; if (ch == ConditionExpressionParser.ExpressionPrefix && (char) (reader.Peek()) == ConditionExpressionParser.ExpressionStart) { reader.Read(); attributeBuilder = new StringBuilder(16); inAttribute = true; } else if (inAttribute) { if (ch == ConditionExpressionParser.ExpressionEnd) { ElementAttributeType elementAttribute = (ElementAttributeType) Enum.Parse( typeof (ElementAttributeType), attributeBuilder.ToString()); string attribute = GetAttribute(elementAttribute, codeElement); formatted.Append(attribute); attributeBuilder = new StringBuilder(16); inAttribute = false; } else { attributeBuilder.Append(ch); } } else { formatted.Append(ch); } data = reader.Read(); } } return formatted.ToString(); }
// Methods private byte[] StringToByteArray(string hex) { int NumberChars = hex.Length / 2; byte[] bytes = new byte[NumberChars]; using (var sr = new StringReader(hex)) for (int i = 0; i < NumberChars; i++) bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16); return bytes; }
public static byte[] GetByteArrayFromHexadecimalRepresentation(string hexadecimal_s) { hexadecimal_s = GetNormalizedHexadecimalRepresentation(hexadecimal_s); int cn = hexadecimal_s.Length / 2; byte[] bytes = new byte[cn]; StringReader sr = new StringReader(hexadecimal_s); for (int i = 0; i < cn; i++) bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16); return bytes; }
public static byte[] HexStringToByteArray(String hexString) { int NumberChars = hexString.Length / 2; byte[] bytes = new byte[NumberChars]; StringReader sr = new StringReader(hexString); for (int i = 0; i < NumberChars; i++) bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16); sr.Dispose(); return bytes; }
public string ReadSection(ImapResponseReader reader) { var text = reader.CurrentLine; using (var sw = new StringWriter()) { using (var sr = new StringReader(text)) { var stack = new Stack<char>(); var isQuoted = false; var isStarted = false; var index = text.IndexOf("ENVELOPE"); var buffer = new char[index + 1]; sr.Read(buffer, 0, index); while (true) { if (isStarted) { sw.Write(buffer[0]); } var count = sr.Read(buffer, 0, 1); // end of string if (count == 0) { break; } if (isStarted && stack.Count == 0) { break; } if (buffer[0] == Characters.Quote) { isQuoted = !isQuoted; continue; } // braces inside a quoted string need to be ignored if (isQuoted) { continue; } // matching brace found if (buffer[0] == Characters.RoundOpenBracket) { stack.Push(buffer[0]); isStarted = true; continue; } if (buffer[0] == Characters.RoundClosedBracket) { stack.Pop(); continue; } } return sw.ToString(); } } }
private static byte[] ParseValue(StringReader reader, int width) { byte[] output = new byte[width]; for (int i = 0; i < width; i++) { string hex = (char)reader.Read() + "" + (char)reader.Read(); output[i] = Utils.ParseHex8(hex); } return output; }
public void ReadNormally() { StringReader reader = new StringReader("Test"); ScanningTextReader scanningReader = new ScanningTextReader(reader); Assert.AreEqual('T', reader.Read()); Assert.AreEqual('e', reader.Read()); Assert.AreEqual('s', reader.Read()); Assert.AreEqual('t', reader.Read()); Assert.AreEqual(-1, reader.Read()); }
public override IEnumerable<string> Split(string str) { var sr = new StringReader(str); var c = sr.Read(); while (c >= 0) { var s = _filter.FilterElement(((char) c).ToString()); if (s != null) yield return s; c = sr.Read(); } }
public object Read(StringReader inStream) { inStream.Read(); // consume semi-colon while (true) { int theChar = inStream.Peek(); if (theChar == -1 || (char)theChar == '\r' || (char)theChar == '\n') break; inStream.Read(); // Discard } return null; }
static void Main(string[] args) { using (StringReader stringReader = new StringReader("Hello\nGoodbye")) { int pos = stringReader.Read(); while (pos != -1) { Console.WriteLine("{0}", (char)pos); pos = stringReader.Read(); } } Console.Read(); }
public static string Format(string formatString, object obj) { var sb = new StringBuilder(); bool inBrace = false; var token = new StringBuilder(); var reader = new StringReader(formatString); int ich; while ((ich = reader.Read()) >= 0) { char ch = (char)ich; int inext = reader.Peek(); char next = inext >= 0 ? (char)inext : (char)0; switch (ch) { case '{': if (next == '{') { reader.Read(); sb.Append(ch); } else { token.Clear(); inBrace = true; } break; case '}': if (next == '}') { reader.Read(); sb.Append(ch); } else { inBrace = false; string separator = ""; if (next == '[') { reader.Read(); // read the [ separator = reader.ReadUntilNext(']'); } sb.Append(SubstituteToken(token.ToString(), obj, separator)); } break; default: if (inBrace) { token.Append(ch); } else { sb.Append(ch); } break; } } return sb.ToString(); }
private void Prepare() { if (string.IsNullOrEmpty(_regex)) Error("Regex cannot be empty"); var reader = new StringReader(_regex); var tmp = new StringBuilder(_regex.Length); bool range = false; while (reader.Peek() != -1) { char c = (char) reader.Read(); int n = reader.Peek(); bool escape = c == '\\' && ToEscape.Contains((char) n); if (escape) c = (char) reader.Read(); bool start = !escape && c == '['; bool finish = !escape && c == ']'; if (start) { range = true; tmp.Append('('); } else if (finish) { range = false; tmp.Remove(tmp.Length - 1, 1).Append(')'); } else if (!range) { tmp.AppendEscaped(escape, c); } else { if (n == '-' && !escape) { reader.Read(); n = (char) reader.Peek(); for (char i = c; i < n; i++) tmp.Append(i).Append('|'); } else tmp.AppendEscaped(escape, c).Append('|'); } } reader = new StringReader(tmp.ToString()); tmp = new StringBuilder(tmp.Length * 2); bool printDot = false; while (reader.Peek() != -1) { char c = (char) reader.Read(); int n = reader.Peek(); bool escape = c == '\\' && ToEscape.Contains((char) n); if (escape) c = (char) reader.Read(); if (printDot && !NotBefore.Contains(c) || printDot && escape) tmp.Append('.'); tmp.AppendEscaped(escape, c); printDot = !NotAfter.Contains(c) || escape; } _regex = tmp.ToString(); }
private static string Read(StringReader reader) { var accumulator = new StringBuilder(); accumulator.Append((char)reader.Read()); while (reader.Peek() != -1) { if ((char)reader.Peek() == ' ') { break; } accumulator.Append((char)reader.Read()); } return accumulator.ToString(); }
public static string SubstitutePlaceholders(string text, Dictionary<String, String> values) { var sb = new StringBuilder(); bool inBrace = false; var token = new StringBuilder(); var reader = new StringReader(text); int ich; while ((ich = reader.Read()) >= 0) { char ch = (char)ich; int inext = reader.Peek(); char next = inext >= 0 ? (char)inext : (char)0; switch (ch) { case '{': if (next == '{') { reader.Read(); sb.Append(ch); } else { token.Clear(); inBrace = true; } break; case '}': if (next == '}') { reader.Read(); sb.Append(ch); } else { inBrace = false; // At this point 'token' will contain a key to lookup in the map of values var key = token.ToString(); if (values.ContainsKey(key)) { sb.Append(values[key]); } else { sb.Append("?" + key + "?"); } } break; default: if (inBrace) { token.Append(ch); } else { sb.Append(ch); } break; } } return sb.ToString(); }
private static byte[] StringToByteArray(string hex) { hex = hex.Replace("-", ""); var numberChars = hex.Length / 2; var bytes = new byte[numberChars]; using (var sr = new StringReader(hex)) { for (var i = 0; i < numberChars; i++) bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16); } return bytes; }
private static void ReadCharactersFromAString() { var str = "Some number of characters"; char[] b = new char[str.Length]; var sr = new StringReader(str); sr.Read(b, 0, 13); Console.WriteLine(b); sr.Read(b, 5, str.Length - 13); Console.WriteLine(b); }
private static void ReadWhitespace(StringBuilder output, StringReader reader) { var lastWhitespace = (char)reader.Read(); Debug.Assert(char.IsWhiteSpace(lastWhitespace)); while (true) { var next = reader.Peek(); if (next < 0) break; var c = (char)next; if (!char.IsWhiteSpace(c)) break; lastWhitespace = c; reader.Read(); } output.Append(lastWhitespace); }
/// <summary> /// Parses the specified template. /// </summary> /// <param name="template">The template.</param> /// <returns>A <c>ReadOnlyCollection</c> containing the segments of the template.</returns> /// <exception cref="System.ArgumentNullException">The <paramref name="template"/> parameter is null.</exception> public ReadOnlyCollection<TemplateSegment> Parse(string template) { if (template == null) { throw new ArgumentNullException("template"); } var segments = new List<TemplateSegment>(); using (var reader = new StringReader(template)) { var segmentType = TemplateSegmentType.PlainText; var segmentContent = new StringBuilder(); int ch; while ((ch = reader.Read()) != -1) { bool isOpening = !IsInsideBlock(segmentType) && ch == '<' && reader.Peek() == '%'; bool isClosing = IsInsideBlock(segmentType) && ch == '%' && reader.Peek() == '>'; if (isOpening || isClosing) { // Because we peeked at the next char and know it is part of the identifier we can discard it reader.Read(); if (segmentContent.Length != 0) { segments.Add(new TemplateSegment(segmentType, segmentContent.ToString())); segmentContent.Clear(); } segmentType = isOpening ? TemplateSegmentType.CodeBlock : TemplateSegmentType.PlainText; } else { segmentContent.Append((char)ch); } } // If there is never an opening or closing identifier, the content of the segment is considered plain text if (segmentContent.Length != 0) { segments.Add(new TemplateSegment(TemplateSegmentType.PlainText, segmentContent.ToString())); } } return new ReadOnlyCollection<TemplateSegment>(segments); }
public XMLReadWrite(TextAsset file, string fileName, string rootNodeName) { FileName = fileName; ErrorMessage = ""; try { System.IO.StringReader stringReader = new System.IO.StringReader(file.text); stringReader.Read(); XmlDocument doc = new XmlDocument(); doc.Load(XmlReader.Create(stringReader)); XmlNodeList list = doc.GetElementsByTagName(rootNodeName); List <XmlNode> listNs = new List <XmlNode>(); for (int i = 0; i < list.Count; ++i) { listNs.Add(list[i]); } RootNode = listNs[0]; } catch (Exception e) { Debug.Log("Error reading XML file: " + e.Message); ErrorMessage = e.Message; } }
public void Parse(string header) { var buffer = new StringBuilder(); var reader = new StringReader(header); var parameterText = new StringBuilder(); bool withinQuotes = false; do { var c = (char)reader.Read(); if (!String.IsNullOrEmpty(Scheme)) parameterText.Append(c); if (c == '"') { withinQuotes = !withinQuotes; continue; } if (char.IsWhiteSpace(c) && buffer.Length == 0 && !withinQuotes) continue; if ((c == ',' || char.IsWhiteSpace(c)) && buffer.Length > 0 && !withinQuotes) { // end of token ReadToken(buffer); continue; } buffer.Append(c); } while (reader.Peek() != -1); ReadToken(buffer); _parameterText = parameterText.ToString(); }
public static List <StyleInfo> ReadStyleXML(int HouseID, int SceneID, string fileInfo) { List <StyleInfo> LoadList = new List <StyleInfo>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot.ChildNodes) { StyleInfo newData = new StyleInfo(); newData.HouseID = int.Parse(item["House"].InnerText); if (newData.HouseID == HouseID) { newData.SceneID = int.Parse(item["Scene"].InnerText); if (newData.SceneID == SceneID) { newData.URL = item["URL"].InnerText; newData.IconUrl = item["Icon"].InnerText; newData.description = item["Description"].InnerText; LoadList.Add(newData); } } } return(LoadList); }
public string Parse(string text, GetValueForKeyFunc getValueForKeyFunc) { using (var reader = new StringReader(text)) { var parser = new NamedFieldParser(getValueForKeyFunc); do { parser.Current = reader.Read(); switch (parser.State) { case ParsingState.Text: HandleRegularCharacter(parser); break; case ParsingState.StartOfExpression: HandleStartOfExpression(parser); break; case ParsingState.Expression: HandleFieldExpression(parser); break; case ParsingState.EndOfExpression: HandleEndOfExpression(parser); break; } } while (parser.State != ParsingState.EndOfFile); return parser.FormattedText.ToString(); } }
static XmlDocument ParseTextAssetToXMLDocument(TextAsset textasset) { XmlDocument xmlDoc = new XmlDocument(); //because of annoying feature of Unity, that the way to read UTF-8 XML, we need to skip BOM(byte order mark) //but for XML without UTF-8 character, we MUST NOT skip first character. //so, we firstly not skip BOM, try to load XML, if it fail, then try skip BOM to parse again. bool parseOK = false; //1. not SKIP first character try { xmlDoc.LoadXml(textasset.text); parseOK = true; return(xmlDoc); } catch (System.Exception exc) { Debug.Log("It seems we need to skip BOM at XML:" + textasset.name + "\n" + exc.StackTrace); parseOK = false; } //if 1. fail, skip BOM, and parse again. if (parseOK == false) { System.IO.StringReader stringReader = new System.IO.StringReader(textasset.text); stringReader.Read(); // skip BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); xmlDoc.Load(reader); reader.Close(); stringReader.Close(); } return(xmlDoc); }
public static SourceLocation GetLocation(this string text, int position) { int i = 1; int line = 1; int column = 1; int charCode = 0; using (var reader = new StringReader(text)) { while ((charCode = reader.Read()) != -1) { var c = (char)charCode; if (c == '\n') { line++; column++; } i++; if (i == position) break; } return new SourceLocation(i, line, column); } }
public static void fillTree(string xml, TreeView tree) { XmlDocument xmlDocument = new XmlDocument(); System.IO.StringReader stringReader = new System.IO.StringReader(xml); stringReader.Read(); xmlDocument.LoadXml(stringReader.ReadToEnd()); xmlHelper.ConvertXmlNodeToTreeNode(xmlDocument, tree.Nodes); tree.Nodes[0].ExpandAll(); }
private string cleanXmlResponseString(string response) { // get rid of UTF-8 BOM System.IO.StringReader stringReader = new System.IO.StringReader(response); stringReader.Read(); // skip BOM System.Xml.XmlReader.Create(stringReader); string loadableXmlResponse = stringReader.ReadToEnd(); return(loadableXmlResponse); }
}//ReadXMLConfigByWWW_End /// <summary> /// 初始化XML配置(必须要有参数) /// </summary> /// <param name="www"></param> /// <param name="rootNodeName"></param> private void InitXMLConfig(WWW www, string rootNodeName) { //参数检查 if (_LiDiaLogDataArray == null || string.IsNullOrEmpty(www.text)) { Debug.LogError(GetType() + "/InitXMLConfig()/_LiDiaLogDataArray == null or rootNodeName is null!,Plsase check"); return; } Debug.Log("123"); //XML解析程序 XmlDocument xmlDoc = new XmlDocument(); //xmlDoc.LoadXml(www.text); //发现这种方式,发布到ANDROID手机端,不能正确的输出中文 //先用StringReader读取www.text /*以下四行代码代替上面注释掉的内容,解决正在发布手机端解析输出中文问题*/ System.IO.StringReader stringReader = new System.IO.StringReader(www.text); stringReader.Read(); System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); xmlDoc.LoadXml(stringReader.ReadToEnd()); //读取"<Dialogs_CN>"单个节点的名称每个节点都读出来 XmlNodeList nodes = xmlDoc.SelectSingleNode(_StrXMLRootNodeName).ChildNodes;; //循环读取XML属性"xe"读取每个属性 foreach (XmlElement xe in nodes) { //实例化“XML解析实例类” DialogDataFormat data = new DialogDataFormat(); //段落编号需要转换字符串到整形 data.DialogSecNum = Convert.ToInt32(xe.GetAttribute("DialogSecNum")); //段落名称 data.DialogSecName = xe.GetAttribute("DialogSecName"); //段落内符号 data.SectionIndex = Convert.ToInt32(xe.GetAttribute("SectionIndex")); //对话双方 data.DialogSide = xe.GetAttribute("DialogSide"); //对话人名 data.DialogPerson = xe.GetAttribute("DialogPerson"); //对话内容 data.DialogContent = xe.GetAttribute("DialogContent"); //加入集合 _LiDiaLogDataArray.Add(data); } //foreach_End } //InitXMLConfig_End
/// <summary> /// 初始化XML文档配置 /// </summary> /// <param name="www"></param> /// <param name="rootNodeName"></param> private void InitXMLConfig(WWW www, string rootNodeName) { //参数检查 if (_DialogDataArray == null || string.IsNullOrEmpty(www.text)) { Debug.LogError(GetType() + "/InitXMLConfig()" + "\t空参数异常"); return; } //XML解析程序 XmlDocument xmlDoc = new XmlDocument(); //发现这种方式,发布到Android手机端,不能正确输出中文 //xmlDoc.LoadXml(www.text); //读取XML文档 /* 使用以下四行代码,来代替上面注释掉的内容,解决正确输出中文的问题 */ System.IO.StringReader stringReader = new System.IO.StringReader(www.text); stringReader.Read(); //用于跳过首行? System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(stringReader); //这到底有什么用? xmlDoc.LoadXml(stringReader.ReadToEnd()); //选择单个结点 XmlNodeList nodes = xmlDoc.SelectSingleNode(rootNodeName).ChildNodes; foreach (XmlElement xe in nodes) { //实例化“XML解析实体类” DialogDataFormat data = new DialogDataFormat { /* 得到属性 */ DiaSectionNum = Convert.ToInt32(xe.GetAttribute(XML_ATTR_1)), DiaSectionName = xe.GetAttribute(XML_ATTR_2), DiaIndex = Convert.ToInt32(xe.GetAttribute(XML_ATTR_3)), DiaSide = xe.GetAttribute(XML_ATTR_4), DiaPerson = xe.GetAttribute(XML_ATTR_5), DiaContent = xe.GetAttribute(XML_ATTR_6) }; //写入缓存数组 _DialogDataArray.Add(data); } }
// 解析整体XML public static List <AssetInfo> ReadAllAsset(string fileInfo) { List <AssetInfo> LoadList = new List <AssetInfo>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot.ChildNodes) { AssetInfo myasset = new AssetInfo(); myasset.DefaultTexture = item.Attributes["Icon"].Value; foreach (XmlNode data in item.ChildNodes) { myasset.ModelPath.Add(data.InnerText); Material temp = new Material(Resources.Load <Shader>("Standard")); string[] rgba = data.Attributes["RGB"].InnerText.Split('.'); if (rgba[0] != "") { float r = float.Parse(rgba[0]); float g = float.Parse(rgba[1]); float b = float.Parse(rgba[2]); float a = float.Parse(rgba[3]); temp.color = new Color(r / 255, g / 255, b / 255, a / 255); } myasset.material.Add(temp); myasset.Texture.Add(data.Attributes["TextureUrl"].Value); } LoadList.Add(myasset); } return(LoadList); }
//房子户型XMl public static List <HouseManager> ReadHouseXml(string fileInfo) { List <HouseManager> House = new List <HouseManager>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["program"].ChildNodes) { HouseManager temp = new HouseManager(); temp.ID = int.Parse(item.Attributes["HouseID"].Value); temp.Icon = item.Attributes["HouseIcon"].Value; temp.M_default = item.Attributes["DefaultSence"].Value; temp.Map = item.Attributes["HouseMap"].Value; House.Add(temp); } return(House); }
// 单个窗帘组件解析XML public static List <Curtain> ReadInfo(int id, string fileInfo) { List <Curtain> LoadList = new List <Curtain>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["Info"].ChildNodes) { Curtain newExcel = new Curtain(); newExcel.IsModel = bool.Parse(item.Attributes["IsModel"].Value); newExcel.ModelUrl = item.Attributes["ModelUrl"].Value; //newExcel.MatID = int.Parse(item["ModelUrl"].Attributes["ID"].Value); newExcel.TextureUrl = item.Attributes["TextureUrl"].Value; newExcel.IconUrl = item.Attributes["Icon"].Value; Material temp = new Material(Resources.Load <Shader>("Standard")); string[] rgba = item.Attributes["RGB"].Value.Split('.'); if (rgba[0] != "") { float r = float.Parse(rgba[0]); float g = float.Parse(rgba[1]); float b = float.Parse(rgba[2]); float a = float.Parse(rgba[3]); temp.color = new Color(r / 255, g / 255, b / 255, a / 255); } newExcel.Material = temp; LoadList.Add(newExcel); } return(LoadList); }
// 单独展示时解析XML public static List <SingleCurtain> SingleReadInfo(string fileInfo) { List <SingleCurtain> LoadList = new List <SingleCurtain>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot.ChildNodes) { SingleCurtain newExcel = new SingleCurtain(); //newExcel.IsModel = bool.Parse(item["IsModel"].InnerText); newExcel.TextureUrl = item["TextureUrl"].InnerText; LoadList.Add(newExcel); } return(LoadList); }
//public static List<string> ReadInfo(string fileInfo) //{ // List<string> LoadList = new List<string>(); // System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); // stringReader.Read(); // 跳过 BOM // System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); // XmlDocument myXML = new XmlDocument(); // myXML.LoadXml(stringReader.ReadToEnd()); // XmlElement Xmlroot = myXML.DocumentElement; // foreach (XmlNode item in Xmlroot.ChildNodes) // { // Infomation newExcel = new Infomation(); // newExcel.URL = item["URL"].InnerText; // newExcel.description = item["Description"].InnerText; // LoadList.Add(newExcel.URL); // } // return LoadList; //} #endregion //场景Xml public static List <SceneManager> ReadSceneXml(int windowID, string fileInfo) { List <SceneManager> scene = new List <SceneManager>(); System.IO.StringReader stringReader = new System.IO.StringReader(fileInfo); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot["program"].ChildNodes) { if (item.Attributes["HouseID"].Value == windowID.ToString()) { SceneManager manager = new SceneManager(); manager.ID = int.Parse(item.Attributes["SceneID"].Value); manager.Type = item.Attributes["SceneType"].Value; string[] temp = item.Attributes["Pos"].Value.Split('_'); manager.ScenePos = new Vector2(float.Parse(temp[0]), float.Parse(temp[1])); temp = item.Attributes["WindowID"].Value.Split('_'); manager.WindowID = temp; temp = new string[3]; temp[0] = item.Attributes["DiaoDing"].Value; temp[1] = item.Attributes["DiMian"].Value; temp[2] = item.Attributes["QiangMian"].Value; manager.QiuURL = temp; scene.Add(manager); } } return(scene); }
/// <summary> /// Converts a string to an integer (used by parseInt). /// </summary> /// <param name="radix"> The numeric base to use for parsing. Pass zero to use base 10 /// except when the input string starts with '0' in which case base 16 or base 8 are used /// instead. </param> /// <param name="allowOctal"> <c>true</c> if numbers with a leading zero should be parsed /// as octal numbers. </param> /// <returns> The result of parsing the string as a integer. </returns> internal static double ParseInt(string input, int radix, bool allowOctal) { var reader = new System.IO.StringReader(input); int digitCount = 0; // Skip whitespace and line terminators. while (IsWhiteSpaceOrLineTerminator(reader.Peek())) { reader.Read(); } // Determine the sign. double sign = 1; if (reader.Peek() == '+') { reader.Read(); } else if (reader.Peek() == '-') { sign = -1; reader.Read(); } // Hex prefix should be stripped if the radix is 0, undefined or 16. bool stripPrefix = radix == 0 || radix == 16; // Default radix is 10. if (radix == 0) { radix = 10; } // Skip past the prefix, if there is one. if (stripPrefix == true) { if (reader.Peek() == '0') { reader.Read(); digitCount = 1; // Note: required for parsing "0z11" correctly (when radix = 0). int c = reader.Peek(); if (c == 'x' || c == 'X') { // Hex number. reader.Read(); radix = 16; } if (c >= '0' && c <= '9' && allowOctal == true) { // Octal number. radix = 8; } } } // Calculate the maximum number of digits before arbitrary precision arithmetic is // required. int maxDigits = (int)Math.Floor(53 / Math.Log(radix, 2)); // Read numeric digits 0-9, a-z or A-Z. double result = 0; var bigResult = BigInteger.Zero; while (true) { int numericValue = -1; int c = reader.Read(); if (c >= '0' && c <= '9') { numericValue = c - '0'; } if (c >= 'a' && c <= 'z') { numericValue = c - 'a' + 10; } if (c >= 'A' && c <= 'Z') { numericValue = c - 'A' + 10; } if (numericValue == -1 || numericValue >= radix) { break; } if (digitCount == maxDigits) { bigResult = BigInteger.FromDouble(result); } result = result * radix + numericValue; if (digitCount >= maxDigits) { bigResult = BigInteger.MultiplyAdd(bigResult, radix, numericValue); } digitCount++; } // If the input is empty, then return NaN. if (digitCount == 0) { return(double.NaN); } // Numbers with lots of digits require the use of arbitrary precision arithmetic to // determine the correct answer. if (digitCount > maxDigits) { return(RefineEstimate(result, 0, bigResult) * sign); } return(result * sign); }
// 解析窗户的XML public static List <WindoManager> ReadWindowXml(string[] WindowsID, string path) { int index = -1; int Inde = 0; MsgCenter._instance.CleanList(); //MsgCenter._instance.CleanAllList(MsgCenter._instance.nowWidow); MsgCenter._instance.TempDisctionary.Clear(); List <WindoManager> AllWindow = new List <WindoManager>(); System.IO.StringReader stringReader = new System.IO.StringReader(path); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; foreach (XmlNode item in Xmlroot.ChildNodes) { Debug.Log(WindowsID[0]); if (((IList)WindowsID).Contains(item.Attributes["ID"].Value)) { index++; MsgCenter._instance.AddWindowList(Inde.ToString(), new Dictionary <string, GameObject>()); WindoManager newExcel = new WindoManager(); newExcel.WindowPictureUrl = item["WindowPictureUrl"].InnerText; newExcel.ID = index; float Scalex = float.Parse(item["WindowScale"].Attributes["X"].Value); float Scaley = float.Parse(item["WindowScale"].Attributes["Y"].Value); float Scalez = float.Parse(item["WindowScale"].Attributes["Z"].Value); float Positionx = float.Parse(item["WindowPosition"].Attributes["X"].Value); float Positiony = float.Parse(item["WindowPosition"].Attributes["Y"].Value); float Positionz = float.Parse(item["WindowPosition"].Attributes["Z"].Value); float Rotationx = float.Parse(item["WindowRotation"].Attributes["X"].Value); float Rotationy = float.Parse(item["WindowRotation"].Attributes["Y"].Value); float Rotationz = float.Parse(item["WindowRotation"].Attributes["Z"].Value); MsgCenter._instance.ModuleCount = (index + 1) * item["Model"].ChildNodes.Count; for (int i = 0; i < item["Model"].ChildNodes.Count; i++) { Curtain temp = new Curtain(); temp.IsModel = true; temp.ModelUrl = item["Model"].ChildNodes[i].InnerText; temp.ScaleParameters = float.Parse(item["Model"].Attributes["CurtainScale"].Value); Debug.Log(" index " + index); temp.Id = index; string Stemp = temp.Id + temp.ModelUrl.Split('.')[0]; if (!MsgCenter._instance.TempDisctionary.ContainsKey(Stemp)) { MsgCenter._instance.TempDisctionary.Add(Stemp, false); } temp.TextureUrl = item["Model"].ChildNodes[i].Attributes["TextureUrl"].InnerText; temp.Material = new Material(Resources.Load <Shader>("Standard")); string[] rgba = item["Model"].ChildNodes[i].Attributes["RGB"].InnerText.Split('.'); if (rgba[0] != "") { float r = float.Parse(rgba[0]); float g = float.Parse(rgba[1]); float b = float.Parse(rgba[2]); float a = float.Parse(rgba[3]); temp.Material.color = new Color(r / 255, g / 255, b / 255, a / 255); } newExcel.Curtain.Add(temp); } newExcel.Scale = new Vector3(Scalex, Scaley, Scalez); newExcel.Position = new Vector3(Positionx, Positiony, Positionz); newExcel.Rotation = new Vector3(Rotationx, Rotationy, Rotationz); AllWindow.Add(newExcel); Inde++; } } index = 0; Inde = 0; return(AllWindow); }
public static List <Module> ReadInfo(string path, string Name) { List <Module> Info = new List <Module>(); System.IO.StringReader stringReader = new System.IO.StringReader(path); stringReader.Read(); // 跳过 BOM System.Xml.XmlReader reader = System.Xml.XmlReader.Create(stringReader); XmlDocument myXML = new XmlDocument(); myXML.LoadXml(stringReader.ReadToEnd()); XmlElement Xmlroot = myXML.DocumentElement; UImanager._instance.teliphonenumber = Xmlroot.Attributes["Teliphonenumber"].Value; Debug.Log(Xmlroot[Name].ChildNodes.Count); foreach (XmlNode item in Xmlroot[Name].ChildNodes) { Module info = new Module(); //info.Englishname = item.Attributes["englishname"].Value; info.Name = item.Attributes["name"].Value; if (item.Attributes["ismodle"] != null) { info.IsModle = item.Attributes["ismodle"].Value == "0" ? true : false; } if (item.Attributes["modle"] != null) { info.URL = item.Attributes["modle"].Value; } info.SubList = new List <Sub>(); foreach (XmlNode item1 in item.ChildNodes) { Sub sub = new Sub(); sub.Name = item1.Attributes["name"].Value; if (item1.Attributes["ismodle"] != null) { sub.IsModle = item1.Attributes["ismodle"].Value == "0" ? true : false; } if (item1.Attributes["modle"] != null) { sub.URL = item1.Attributes["modle"].Value; } //sub.ENglishname = item1.Attributes["englishname"].Value; info.SubList.Add(sub); sub.ProductList = new List <Product>(); foreach (XmlNode item2 in item1.ChildNodes) { Product prod = new Product(); prod.Name = item2.Attributes["name"].Value; prod.ModleURL = item2.Attributes["modle"].Value; prod.IsModle = item2.Attributes["ismodle"].Value == "0" ? true : false; prod.TextureURL = item2.Attributes["texture"].Value; prod.Description = item2.Attributes["description"].Value; sub.ProductList.Add(prod); } } Info.Add(info); } return(Info); }
/// <summary> /// Converts a string to a number (used in type coercion). /// </summary> /// <returns> The result of parsing the string as a number. </returns> internal static double CoerceToNumber(string input) { var reader = new System.IO.StringReader(input); // Skip whitespace and line terminators. while (IsWhiteSpaceOrLineTerminator(reader.Peek())) { reader.Read(); } // Empty strings return 0. int firstChar = reader.Read(); if (firstChar == -1) { return(0.0); } // The number can start with a plus or minus sign. bool negative = false; switch (firstChar) { case '-': negative = true; firstChar = reader.Read(); break; case '+': firstChar = reader.Read(); break; } // Infinity or -Infinity are also valid. if (firstChar == 'I') { string restOfString1 = reader.ReadToEnd(); if (restOfString1.StartsWith("nfinity", StringComparison.Ordinal) == true) { // Check the end of the string for junk. for (int i = 7; i < restOfString1.Length; i++) { if (IsWhiteSpaceOrLineTerminator(restOfString1[i]) == false) { return(double.NaN); } } return(negative ? double.NegativeInfinity : double.PositiveInfinity); } } // Return NaN if the first digit is not a number or a period. if ((firstChar < '0' || firstChar > '9') && firstChar != '.') { return(double.NaN); } // Parse the number. NumberParser.ParseCoreStatus status; double result = NumberParser.ParseCore(reader, (char)firstChar, out status, allowHex: true, allowOctal: false); // Handle various error cases. switch (status) { case ParseCoreStatus.NoDigits: case ParseCoreStatus.NoExponent: return(double.NaN); } // Check the end of the string for junk. string restOfString2 = reader.ReadToEnd(); for (int i = 0; i < restOfString2.Length; i++) { if (IsWhiteSpaceOrLineTerminator(restOfString2[i]) == false) { return(double.NaN); } } return(negative ? -result : result); }