1

It has taken a while, but I have finally been able to modify an XML document based on user input for the namespace and node name:

string nodeName = "DefinitionName"; // this is really provided by the user
string namespace = "http://schemas.datacontract.org/2004/07/Xxx.Session";  // also user-provided

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(taskResolved.XmlPathAndFileName);
XmlElement rootElement = xmlDocument.DocumentElement;
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
namespaceManager.AddNamespace("snuh", namespace);  // hard-coded prefix, grrr...

XmlNodeList xmlNodes;

xmlNodes = rootElement.SelectNodes("//snuh:" + nodeName, namespaceManager);

I feel like I'm doing something wrong because I have to hard-code a prefix (snuh). I could try and choose a prefix, like snuh, that I can hope will never appear in a document, but that isn't foolproof. Another option is to use a GUID for a prefix, but this just seems like a hack work-around. Am I missing something? Is there a better way?

The top of the XML doc looks like this:

<?xml version="1.0" encoding="utf-8"?>
<SessionStateInfo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="1"
    z:Type="Xxx.SessionStateInfo"
    z:Assembly="Xxx.Common, Version=6.2.0.0, Culture=neutral, PublicKeyToken=null"
    xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"
    xmlns="http://schemas.datacontract.org/2004/07/Xxx.Session">
      <CoaterNumber>25</CoaterNumber>
      <DefinitionName z:Id="2">TwoLineMarkerDefinition</DefinitionName>
      <EnableManualMode>true</EnableManualMode>

2 Answers 2

2

If you want to simply select the first DefinitionName node.

You may write

XmlNode node = rootElement[nodeName, namespace];

and if you want the whole list:

XmlNodeList nodeList = rootElement.GetElementsByTagName(nodeName, namespace);
Sign up to request clarification or add additional context in comments.

Comments

1

What about using the XPath local-name() and namespace-uri() functions?

string xpath = string.Format("//*[local-name()='{0}' and namespace-uri()='{1}']", nodeName, namespace);
xmlNodes = rootElement.SelectNodes(xpath);

Don't know if those functions are supported in XmlDocument though, haven't tested it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.