GetOptionalAttributeValue() public static method

Get an optional attribute value from an XmlNode.
public static GetOptionalAttributeValue ( XmlNode node, string attrName ) : string
node System.Xml.XmlNode The XmlNode to look in.
attrName string The attribute to find.
return string
コード例 #1
0
 private string GetTxtAtributeValue(XmlNode node)
 {
     return(XmlUtils.GetOptionalAttributeValue(
                node,
                "txt",
                XmlUtils.GetManditoryAttributeValue(node, "id")));         // 'id' is default, if no 'txt' attribute is present.
 }
コード例 #2
0
        public void IndentedOverride()
        {
            // simulate a path to the Antonymns
            XmlNode rootLayout      = root.SelectSingleNode("layout[@name=\"Test1\"]");
            XmlNode sensesPartRef   = rootLayout.SelectSingleNode("part[@ref=\"Senses\"]");
            XmlNode antonymnPartRef = sensesPartRef.SelectSingleNode("indent/part[@ref=\"Antonymns\"]");

            object[] path = { rootLayout, 1, sensesPartRef, 2, antonymnPartRef };
            XmlNode  finalPartref;
            XmlNode  result = Inventory.MakeOverride(path, "visibility", "ifdata", 1, out finalPartref);

            Assert.AreEqual(rootLayout.ChildNodes.Count, result.ChildNodes.Count);
            XmlNode antonymNewPartRef = result.SelectSingleNode("//part[@ref=\"Antonymns\"]");

            Assert.AreEqual("ifdata", XmlUtils.GetOptionalAttributeValue(antonymNewPartRef, "visibility"));
            XmlNode indentNewPartRef = antonymNewPartRef.ParentNode;

            Assert.AreEqual("indent", indentNewPartRef.Name);
            XmlNode sensesNewPartRef = indentNewPartRef.ParentNode;

            Assert.AreEqual("part", sensesNewPartRef.Name);
            Assert.AreEqual("Senses", XmlUtils.GetOptionalAttributeValue(sensesNewPartRef, "ref"));
            XmlNode rootNewLayout = sensesNewPartRef.ParentNode;

            Assert.AreEqual("layout", rootNewLayout.Name);
            Assert.AreEqual(result, rootNewLayout);
        }
コード例 #3
0
        public void LevelThreeOverride()
        {
            // simulate a path to the gloss of a synonym. Include some non-part-ref XML nodes.
            XmlNode rootLayout     = root.SelectSingleNode("layout[@name=\"Test1\"]");
            XmlNode sensesPartRef  = rootLayout.SelectSingleNode("part[@ref=\"Senses\"]");
            XmlNode glossPartRef   = root.SelectSingleNode("part[@ref=\"Gloss\"]");
            XmlNode synPartRef     = root.SelectSingleNode("part[@ref=\"Synonyms\"]");
            XmlNode blahPart       = root.SelectSingleNode("part[@id=\"blah\"]");
            XmlNode nonsenceLayout = root.SelectSingleNode("layout[@id=\"nonsence\"]");

            object[] path = { rootLayout, 1, sensesPartRef, blahPart, nonsenceLayout, synPartRef, 2, glossPartRef };
            XmlNode  finalPartref;
            XmlNode  result = Inventory.MakeOverride(path, "visibility", "ifdata", 1, out finalPartref);

            Assert.AreEqual(rootLayout.ChildNodes.Count, result.ChildNodes.Count);
            XmlNode glossNewPartRef = result.SelectSingleNode("//part[@ref=\"Gloss\"]");

            Assert.AreEqual("ifdata", XmlUtils.GetOptionalAttributeValue(glossNewPartRef, "visibility"));
            XmlNode synNewPartRef = glossNewPartRef.ParentNode;

            Assert.AreEqual("part", synNewPartRef.Name);
            Assert.AreEqual("Synonyms", XmlUtils.GetOptionalAttributeValue(synNewPartRef, "ref"));
            // Should have kept unmodified attributes of this element.
            Assert.AreEqual("TestingParam", XmlUtils.GetOptionalAttributeValue(synNewPartRef, "param"));
            XmlNode sensesNewPartRef = synNewPartRef.ParentNode;

            Assert.AreEqual("part", sensesNewPartRef.Name);
            Assert.AreEqual("Senses", XmlUtils.GetOptionalAttributeValue(sensesNewPartRef, "ref"));
            XmlNode rootNewLayout = sensesNewPartRef.ParentNode;

            Assert.AreEqual("layout", rootNewLayout.Name);
            Assert.AreEqual(result, rootNewLayout);
        }
コード例 #4
0
ファイル: XmlUtils.cs プロジェクト: cambell-prince/FieldWorks
        /// <summary>
        /// Get an obligatory attribute value.
        /// </summary>
        /// <param name="node">The XmlNode to look in.</param>
        /// <param name="attrName">The required attribute to find.</param>
        /// <returns>The value of the attribute.</returns>
        /// <exception cref="ApplicationException">
        /// Thrown when the value is not found in the node.
        /// </exception>
        public static string GetManditoryAttributeValue(XmlNode node, string attrName)
        {
            string retval = XmlUtils.GetOptionalAttributeValue(node, attrName, null);

            if (retval == null)
            {
                throw new ApplicationException("The attribute'"
                                               + attrName
                                               + "' is mandatory, but was missing. "
                                               + node.OuterXml);
            }
            return(retval);
        }
コード例 #5
0
        /// <summary>
        /// This is similar to GetStringWithXPath, but the path argument identifies a
        /// single root node, which contains string elemenents (and optionally others,
        /// which are ignored), each containing id and optionally txt elements.
        /// This is much more efficient than GetStringWithXPath when multiple items
        /// are wanted from the same root node, but only reliable when the path
        /// identifies a single root.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="rootXPathFragment"></param>
        /// <param name="fTrim"></param>
        /// <returns></returns>
        private string GetStringWithRootXPath(string id, string rootXPathFragment, bool fTrim)
        {
            if (fTrim)
            {
                id = id.Trim();
            }
            Dictionary <string, string> items = null;

            if (m_pathsToStrings.ContainsKey(rootXPathFragment))
            {
                items = m_pathsToStrings[rootXPathFragment];
            }
            else
            {
                string path = "strings/" + rootXPathFragment;
                if (path[path.Length - 1] == '/')
                {
                    path = path.Substring(0, path.Length - 1);                     // strip closing slash.
                }
                XmlNode parent = m_document.SelectSingleNode(path);
                items = new Dictionary <string, string>();
                m_pathsToStrings[rootXPathFragment] = items;
                if (parent != null)
                {
                    foreach (XmlNode child in parent.ChildNodes)
                    {
                        string idChild = XmlUtils.GetOptionalAttributeValue(child, "id");
                        //if the txt attribute is missing, use the id attr,
                        //as this is unacceptable shorthand to use for English entries.
                        //e.g.: <string id="Anywhere"/> is equivalent to <string id="Anywhere" txt="Anywhere"/>
                        string txt = XmlUtils.GetOptionalAttributeValue(child, "txt", idChild);
                        if (child.Name == "string" && idChild != null)
                        {
                            items[idChild] = txt;
                        }
                    }
                }
            }
            if (items.ContainsKey(id))
            {
                return(items[id]);
            }

            if (m_parent != null)
            {
                return(m_parent.GetStringWithXPath(id, rootXPathFragment));
            }
            return("*" + id + "*");
        }
コード例 #6
0
        private void MergeCustomGroups(XmlNode parentNode, XmlNodeList customGroupNodeList)
        {
            if (customGroupNodeList == null || customGroupNodeList.Count == 0)
            {
                return;                 // Stop recursing in this method.
            }
            foreach (XmlNode customGroupNode in customGroupNodeList)
            {
                string  customGroupId        = XmlUtils.GetManditoryAttributeValue(customGroupNode, "id");
                XmlNode srcMatchingGroupNode = parentNode.SelectSingleNode("group[@id='" + customGroupId + "']");
                if (srcMatchingGroupNode == null)
                {
                    // Import the entire custom node.
                    m_document.DocumentElement.AppendChild(m_document.ImportNode(customGroupNode, true));
                }
                else
                {
                    // 1. Import new strings, or override extant strings with custom strings.
                    foreach (XmlNode customStringNode in customGroupNode.SelectNodes("string"))
                    {
                        string  customId              = XmlUtils.GetManditoryAttributeValue(customStringNode, "id");
                        string  customTxt             = GetTxtAtributeValue(customStringNode);
                        XmlNode srcMatchingStringNode = srcMatchingGroupNode.SelectSingleNode("string[@id='" + customId + "']");
                        if (srcMatchingStringNode == null)
                        {
                            // Import the new string into the extant group.
                            srcMatchingGroupNode.AppendChild(m_document.ImportNode(customStringNode, true));
                        }
                        else
                        {
                            // Replace the original value with the new value.
                            // The 'txt' attribute is optional, but it will be added as a cpoy of the 'id' here, if needed.
                            string srcTxt = XmlUtils.GetOptionalAttributeValue(srcMatchingStringNode, "txt");
                            if (srcTxt == null)
                            {
                                XmlUtils.AppendAttribute(srcMatchingStringNode, "txt", customTxt);
                            }
                            else
                            {
                                srcMatchingStringNode.Attributes["txt"].Value = customTxt;
                            }
                        }
                    }

                    // 2. Group elements can be nested, so merge them, too.
                    MergeCustomGroups(srcMatchingGroupNode, customGroupNode.SelectNodes("group"));
                }
            }
        }
コード例 #7
0
        public void SimpleOverride()
        {
            // simulate a path to the citation form
            XmlNode rootLayout = root.SelectSingleNode("layout[@name=\"Test1\"]");
            XmlNode cfPartRef  = rootLayout.SelectSingleNode("part[@ref=\"CitationForm\"]");

            object[] path = { rootLayout, cfPartRef };
            XmlNode  finalPartref;
            XmlNode  result = Inventory.MakeOverride(path, "visibility", "ifdata", 7, out finalPartref);

            Assert.AreEqual(rootLayout.ChildNodes.Count, result.ChildNodes.Count);
            XmlNode cfNewPartRef = result.SelectSingleNode("part[@ref=\"CitationForm\"]");

            Assert.AreEqual("ifdata", XmlUtils.GetOptionalAttributeValue(cfNewPartRef, "visibility"));
            Assert.AreEqual("7", XmlUtils.GetOptionalAttributeValue(result, "version"));
        }
コード例 #8
0
        public void OverrideDerived()
        {
            // Check that we can find a base node for a layout derived from an override.
            CheckBaseNode("layout", new string[] { "LexEntry", "jtview", null, "DerivedForOverride" }, "DO2");
            CheckAlterationNode("layout", new string[] { "LexEntry", "jtview", null, "DerivedForOverride" }, "DO3");
            XmlNode unified     = CheckNode("layout", new string[] { "LexEntry", "jtview", null, "DerivedForOverride" }, "DO3");
            XmlNode groupSecond = unified.ChildNodes[1];

            Assert.AreEqual("group", groupSecond.Name, "first child of unified should be a group");
            Assert.AreEqual(2, groupSecond.ChildNodes.Count, "main group should have two chidren");
            Assert.AreEqual("second", XmlUtils.GetOptionalAttributeValue(groupSecond, "label"),
                            "second child should be group 'second'");

            VerifyAttr(groupSecond, "ws", "vernacular");             // inherited from derived element.
            VerifyAttr(groupSecond, "rubbish", "nonsense");          // from override.
        }
コード例 #9
0
        public void Overrides()
        {
            // Check that we can find a base node for a layout derived from an override.
            CheckBaseNode("layout", new string[] { "LexSense", "jtview", null, "Test8D" }, "test7D");
            CheckAlterationNode("layout", new string[] { "LexSense", "jtview", null, "Test8D" }, "test8D");
            XmlNode unified   = CheckNode("layout", new string[] { "LexSense", "jtview", null, "Test8D" }, "test8D");
            XmlNode groupMain = unified.ChildNodes[0];

            Assert.AreEqual("group", groupMain.Name, "first child of unified should be a group");
            Assert.AreEqual(0, groupMain.ChildNodes.Count, "main group should have no chidren");
            Assert.AreEqual("main", XmlUtils.GetOptionalAttributeValue(groupMain, "label"),
                            "first child should be group 'main'");

            VerifyAttr(groupMain, "ws", "analysis");            // inherited from override.
            VerifyAttr(groupMain, "rubbish", "goodstuff");      // overridden.
            VerifyAttr(groupMain, "dummy", "base");             // inherited from original base.
        }
コード例 #10
0
        protected void FindParent(string baseDirectory)
        {
            XmlNode node = m_document.SelectSingleNode("strings");

            if (node == null)
            {
                throw new ApplicationException("Could not find the root node, <strings> in " + baseDirectory);
            }


            string inheritPath = XmlUtils.GetOptionalAttributeValue(node, "inheritPath");

            if (inheritPath != null && inheritPath.Length > 0)
            {
                string path = Path.Combine(baseDirectory, inheritPath);
                m_parent = new StringTable(path);
            }
        }
コード例 #11
0
        /// <summary>
        /// look up a list of string IDs and return an array of strings
        /// </summary>
        /// <example>
        ///		here, the strings will be looked up at the root level
        ///		<stringList ids="anywhere, somewhere to left, somewhere to right, adjacent to left, adjacent to right"/>
        /// </example>
        /// <example>
        ///		here, the strings will be looked up under a nested group
        ///		<stringList group="MoMorphAdhocProhib/adjacency" ids="anywhere, somewhere to left, somewhere to right, adjacent to left, adjacent to right"/>
        /// </example>
        /// <param name="node">the name of the node is ignored, only the attributes are read</param>
        /// <returns></returns>
        public string[] GetStringsFromStringListNode(XmlNode node)
        {
            string ids = XmlUtils.GetManditoryAttributeValue(node, "ids");

            string[] idList     = ids.Split(new char[] { ',' });
            string[] strings    = new string[idList.Length];
            string   groupPath  = "";
            string   simplePath = XmlUtils.GetOptionalAttributeValue(node, "group");

            if (simplePath != null)
            {
                groupPath = GetXPathFragmentFromSimpleNotation(simplePath);
            }
            int i = 0;

            foreach (string id in idList)
            {
                strings[i++] = GetStringWithXPath(id, groupPath);
            }
            return(strings);
        }
コード例 #12
0
ファイル: XmlUtils.cs プロジェクト: cambell-prince/FieldWorks
 /// <summary>
 /// Get an optional attribute value from an XmlNode.
 /// </summary>
 /// <param name="node">The XmlNode to look in.</param>
 /// <param name="attrName">The attribute to find.</param>
 /// <returns>The value of the attribute, or null, if not found.</returns>
 public static string GetAttributeValue(XmlNode node, string attrName)
 {
     return(XmlUtils.GetOptionalAttributeValue(node, attrName));
 }
コード例 #13
0
        public void DerivedElements()
        {
            // Check that we can get a base node for this view BEFORE we have retrieved anything about the layout
            // (a derived one) on which it is based.
            CheckBaseNode("layout", new string[] { "LexEntry", "jtview", null, "Test5D" }, "test1D");
            // Load a file involving derived elements.
            // Check that we can retrieve the base, derived, and unified versions of the elements.
            XmlNode unified  = CheckNode("layout", new string[] { "LexEntry", "jtview", null, "Test1D" }, "test1D");
            XmlNode baseNode = CheckBaseNode("layout", new string[] { "LexEntry", "jtview", null, "Test1D" }, "test3");
            XmlNode derived  = CheckAlterationNode("layout", new string[] { "LexEntry", "jtview", null, "Test1D" }, "test1D");

            Assert.IsNull(m_inventory.GetAlteration("layout", new string[] { "LexEntry", "jtview", null, "Test1" }),
                          "GetAlteration should be null for non-derived node.");

            // Check correct working of unification:
            // - first main child is present as expected
            XmlNode groupMain = unified.ChildNodes[0];

            Assert.AreEqual("group", groupMain.Name, "first child of unified should be a group");
            Assert.AreEqual(3, groupMain.ChildNodes.Count, "main group should have three chidren");
            Assert.AreEqual("main", XmlUtils.GetOptionalAttributeValue(groupMain, "label"),
                            "first child should be group 'main'");
            // - added elements are added. (Also checks default order: original plus extras.)
            // - unmatched original elements are left alone.
            XmlNode part0M = VerifyChild(groupMain, 0, "ref", "LexEntry-Jt-Citationform");
            XmlNode part1M = VerifyChild(groupMain, 1, "ref", "LexEntry-Jt-Senses");
            XmlNode part2M = VerifyChild(groupMain, 2, "ref", "LexEntry-Jt-Forms");

            // - child elements are correctly ordered when 'reorder' is true.
            XmlNode groupSecond = unified.ChildNodes[1];

            Assert.AreEqual("group", groupSecond.Name, "second child of unified should be a group");
            Assert.AreEqual(3, groupSecond.ChildNodes.Count, "main group should have three chidren");
            Assert.AreEqual("second", XmlUtils.GetOptionalAttributeValue(groupSecond, "label"),
                            "second child should be group 'second'");
            XmlNode part0S = VerifyChild(groupSecond, 0, "ref", "LexEntry-Jt-Forms");
            XmlNode part1S = VerifyChild(groupSecond, 1, "ref", "LexEntry-Jt-Citationform");
            XmlNode part2S = VerifyChild(groupSecond, 2, "ref", "LexEntry-Jt-Senses");

            // - check no reordering when no element added, and reorder is false
            XmlNode groupThird = unified.ChildNodes[2];

            Assert.AreEqual("group", groupThird.Name, "Third child of unified should be a group");
            Assert.AreEqual(3, groupThird.ChildNodes.Count, "main group should have three chidren");
            Assert.AreEqual("third", XmlUtils.GetOptionalAttributeValue(groupThird, "label"),
                            "third child should be group 'Third'");
            VerifyChild(groupThird, 0, "ref", "LexEntry-Jt-Citationform");
            VerifyChild(groupThird, 1, "ref", "LexEntry-Jt-Senses");
            VerifyChild(groupThird, 2, "ref", "LexEntry-Jt-Forms");

            // - added attributes are added.
            VerifyAttr(part0M, "part", "default");
            VerifyAttr(part1S, "part", "default");
            VerifyAttr(unified, "dummy", "true");
            // - overridden attributes are replaced.
            VerifyAttr(part0M, "ws", "technical");
            VerifyAttr(part1S, "ws", "technical");
            VerifyAttr(unified, "visible", "never");
            // - attributes not mentioned in override are unchanged.
            VerifyAttr(part0M, "visible", "always");
            VerifyAttr(part1S, "visible", "always");
            VerifyAttr(unified, "ws", "vernacular");
        }
コード例 #14
0
 void VerifyAttr(XmlNode node, string attr, string val)
 {
     Assert.AreEqual(val, XmlUtils.GetOptionalAttributeValue(node, attr));
 }
コード例 #15
0
ファイル: IncludeXml.cs プロジェクト: sillsdev/WorldPad
        /// <summary>
        /// replace the node with the node or nodes that it refers to
        /// </summary>
        /// <example>
        /// <include path='IncludeXmlTestSource.xml' query='food/fruit/name'/>
        /// </example>
        /// <param name="includeNode"></param>
        protected void ReplaceNode(Dictionary <string, XmlDocument> cachedDoms, string parentPath, XmlNode includeNode, string defaultPath)
        {
            string path = null;

            if (defaultPath != null && defaultPath.Length > 0)
            {
                path = XmlUtils.GetOptionalAttributeValue(includeNode, "path", defaultPath);
            }
            else
            {
                path = XmlUtils.GetOptionalAttributeValue(includeNode, "path");
                if (path == null || path.Trim().Length == 0)
                {
                    throw new ApplicationException(
                              "The path attribute was missing and no default path was specified. \r\n"
                              + includeNode.OuterXml);
                }
            }

            XmlNode parentNode = includeNode.ParentNode;

            try
            {
                /* To support extensions, we need to see if 'path' starts with 'Extensions/* /'. (without the extra space following the '*'.)
                 * If it does, then we will have to get any folders (the '*' wildcard)
                 * and see if any of them have the specified file (at end of 'path'.
                 */
                StringCollection paths = new StringCollection();
                // The extension XML files should be stored in the data area, not in the code area.
                // This reduces the need for users to have administrative privileges.
                bool   fExtension       = false;
                string extensionBaseDir = null;
                if (path.StartsWith("Extensions") || path.StartsWith("extensions"))
                {
                    // Extension <include> element,
                    // which may have zero or more actual extensions.
                    string extensionFileName = path.Substring(path.LastIndexOf("/") + 1);
                    string pluginBaseDir     = (parentPath == null) ? m_resolver.BaseDirectory : parentPath;
                    extensionBaseDir = pluginBaseDir;
                    string sBaseCode = DirectoryFinder.FWCodeDirectory;
                    string sBaseData = DirectoryFinder.FWDataDirectory;
                    if (extensionBaseDir.StartsWith(sBaseCode) && sBaseCode != sBaseData)
                    {
                        extensionBaseDir = extensionBaseDir.Replace(sBaseCode, sBaseData);
                    }
                    // JohnT: allow the Extensions directory not even to exist. Just means no extentions, as if empty.
                    if (!Directory.Exists(extensionBaseDir + "/Extensions"))
                    {
                        return;
                    }
                    foreach (string extensionDir in Directory.GetDirectories(extensionBaseDir + "/Extensions"))
                    {
                        string extensionPathname = Path.Combine(extensionDir, extensionFileName);
                        // Add to 'paths' collection, but only from 'Extensions' on.
                        if (File.Exists(extensionPathname))
                        {
                            paths.Add(extensionPathname.Substring(extensionPathname.IndexOf("Extensions")));
                        }
                    }
                    // Check for newer versions of the extension files in the
                    // "Available Plugins" directory.  See LT-8051.
                    UpdateExtensionFilesIfNeeded(paths, pluginBaseDir, extensionBaseDir);
                    if (paths.Count == 0)
                    {
                        return;
                    }
                    fExtension = true;
                }
                else
                {
                    // Standard, non-extension, <include> element.
                    paths.Add(path);
                }

                /* Any fragments (extensions or standard) will be added before the <include>
                 * element. Aftwerwards, the <include> element will be removed.
                 */
                string query = XmlUtils.GetManditoryAttributeValue(includeNode, "query");
                foreach (string innerPath in paths)
                {
                    XmlDocumentFragment fragment;
                    if (innerPath == "$this")
                    {
                        fragment = CreateFragmentWithTargetNodes(query, includeNode.OwnerDocument);
                    }
                    else
                    {
                        fragment = GetTargetNodes(cachedDoms,
                                                  fExtension ? extensionBaseDir : parentPath, innerPath, query);
                    }
                    if (fragment != null)
                    {
                        XmlNode node = includeNode.OwnerDocument.ImportNode(fragment, true);
                        // Since we can't tell the index of includeNode,
                        // always add the fluffed-up node before the include node to keep it/them in the original order.
                        parentNode.InsertBefore(node, includeNode);
                    }
                }
                // Handle any overrides.
                HandleIncludeOverrides(includeNode);
            }
            finally
            {
                // Don't want the original <include> element any more, no matter what.
                parentNode.RemoveChild(includeNode);
            }
        }