示例#1
0
        private static IEnumerable ExpandIncludeNode(XmlDocument ownerDocment, string baseDirectory, List <string> parentFileList, List <string> includeFileList,
                                                     XmlElement element)
        {
            string includeFileName = element.GetAttribute(PathToken);

            if (String.IsNullOrEmpty(includeFileName))
            {
                return new XmlNode[] { }
            }
            ;
            if (!String.IsNullOrEmpty(baseDirectory) && !Path.IsPathRooted(includeFileName))
            {
                includeFileName = Path.Combine(baseDirectory, includeFileName);
            }

            if (!String.IsNullOrEmpty(baseDirectory) && IsCircularFileExists(parentFileList, includeFileName))
            {
                throw new XmlException(String.Format("Circular reference encountered on the {0} file.", baseDirectory));
            }

            if (!includeFileList.Contains(includeFileName))
            {
                includeFileList.Add(includeFileName);
            }

            XmlDocumentFragment fragment = ownerDocment.CreateDocumentFragment();

            try
            {
                XmlDocument includeDoc = new XmlDocument();
                includeDoc.Load(includeFileName);

                foreach (XmlAttribute attr in element.Attributes)
                {
                    if (attr.Name != PathToken)
                    {
                        includeDoc.DocumentElement.SetAttribute(attr.Name, attr.Value);
                    }
                }

                fragment.InnerXml = includeDoc.InnerXml;

                return(new XmlNode[] { fragment.SelectSingleNode("/*") });
            }
            catch (XmlException)
            {
                try
                {
                    using (StreamReader sr = File.OpenText(includeFileName))
                        fragment.InnerXml = sr.ReadToEnd();

                    return(fragment.SelectNodes("/*|/comment()"));
                }
                catch (Exception innerEx)
                {
                    throw new XmlException(String.Format("{0}: Error loading xml file.", includeFileName), innerEx);
                }
            }
            catch (Exception ex)
            {
                throw new XmlException(String.Format("{0}: Error loading xml file.", includeFileName), ex);
            }
        }