質問

I'm trying to add an XML element to a document and i'm getting quite confused with the namespaces. Can someone point out what i'm doing wrong below?

Xml before:

...
<TaxKeywordTaxHTField xmlns="e907f980-2644-454c-b5eb-278bd59dc318">
    <Terms xmlns="http://schemas.microsoft.com/office/infopath/2007/PartnerControls"/>
</TaxKeywordTaxHTField>
...

Xml required after:

...
<TaxKeywordTaxHTField xmlns="e907f980-2644-454c-b5eb-278bd59dc318">
    <Terms xmlns="http://schemas.microsoft.com/office/infopath/2007/PartnerControls">
        <TermInfo xmlns="http://schemas.microsoft.com/office/infopath/2007/PartnerControls">
            <TermName>Kenya</TermName>
            <TermId>283e7636-3eca-4a6c-8ea7-5c1b768b8f2b</TermId>
        </TermInfo>
    </Terms>
</TaxKeywordTaxHTField>
...

My code creates the following:

...
<TaxKeywordTaxHTField xmlns="e907f980-2644-454c-b5eb-278bd59dc318">
    <Terms xmlns="http://schemas.microsoft.com/office/infopath/2007/PartnerControls">
        <TermInfo>
            <TermName xmlns="">Kenya</TermName>
            <TermId xmlns="">283e7636-3eca-4a6c-8ea7-5c1b768b8f2b</TermId>
        </TermInfo>
    </Terms>
</TaxKeywordTaxHTField>
...

Here's my code:

var terms = DocumentManagment.Descendants(ns4 + "TaxKeywordTaxHTField")
                .Descendants(ns2 + "Terms").SingleOrDefault();
terms.AddFirst(
    new XElement(ns2 + "TermInfo",
        new XElement("TermName", "Kenya"),
        new XElement("TermId", "283e7636-3eca-4a6c-8ea7-5c1b768b8f2b")));
役に立ちましたか?

解決

Both TermName and TermId are in namespace "http://schemas.microsoft.com/office/infopath/2007/PartnerControls" so just add this namespace to their names:

 terms.AddFirst(
    new XElement(ns2 + "TermInfo",
        new XElement(ns2 + "TermName", "Kenya"),
        new XElement(ns2 + "TermId", "283e7636-3eca-4a6c-8ea7-5c1b768b8f2b")));

This will produce following xml:

<TaxKeywordTaxHTField xmlns="e907f980-2644-454c-b5eb-278bd59dc318">
  <Terms xmlns="http://schemas.microsoft.com/office/infopath/2007/PartnerControls">
    <TermInfo>
      <TermName>Kenya</TermName>
      <TermId>283e7636-3eca-4a6c-8ea7-5c1b768b8f2b</TermId>
    </TermInfo>
  </Terms>
</TaxKeywordTaxHTField>

Note: thus TermInfo in same default namespace as its parent element, then namespace is just inherited and its not declared explicitly.

Also keep in mind, if you are not specifying namespace for element, then it considered to be in None namespace. But if parent element already defines default namespace, which is inherited by child elements, then this empty namespace should be declared explicitly. That's why you see xmlns="" in your output.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top